import * as Cesium from "cesium";
import CesiumOverviewMapControl from "./CesiumOverviewMapControl";
import AmapMercatorTilingScheme from "./amaptiling";
import MeasureManager from "./MeasureManager";
import CesiumPlot from 'cesium-plot-js';
import axios from "axios";
// import { mStore } from "../../store/index3d";
import { toRaw } from "vue";
import { ElMessage } from "element-plus";
import fluidPolyline from "./migrate";
import fluidPolylinetrend from "./trend";
import mapObj from "./mapObj";
// import WallDiff from "./WallDiffuseMaterialProperty";
import { mainStore } from "../store/index";

Cesium.Ion.defaultAccessToken =
    "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiIwOTc0OWZiMC1kYWFkLTQ3Y2QtODQyNC0wNTdkMTdmMTk4MTEiLCJpZCI6MjIzMTMsImlhdCI6MTYwMjUzOTUxNH0.r18dBOtxmRRuiYcogILHfk3TN7lGrgOfTDSxIYxO9hY";
var viewer = null;
var viewer2 = null;
var m_3dtile;
var m_ServerInof = [];

// var worldTerrain = Cesium.createWorldTerrain({
//     requestWaterMask: true,
//     requestVertexNormals: true,
// });
// var terrainProvider = new Cesium.CesiumTerrainProvider({
//     url: 'http://192.168.10.9:2001/dem/layer.json'
// });
let wapworldToken = "4f84dc2cfc78b3442152aaa133229c3b";
// 服务域名
// 服务负载子域
var m_MeasureManager = null;
function setviewer() {
    viewer = new Cesium.Viewer("cesiumContainer", {
        animation: false, //左下角控制动画
        baseLayerPicker: false, //右上角图层选择器
        fullscreenButton: false,
        geocoder: false, //右上角搜索
        homeButton: false,
        infoBox: false,
        scene3DOnly: true, //仅仅显示3d,可隐藏右上角2d和3d按钮
        selectionoIndicatr: false,
        timeline: true, //最下面时间轴
        navigationHelpButton: false, //右上角帮助按钮
        navigationInstructionsInitiallyVisibl: false,
        useDefaultRenderLoop: true,
        showRenderLoopErrors: true,
        projectionPicker: false,
        shouldAnimate: true,
        selectionIndicator: false,
    });
    mapObj.f_SetMapViewer(viewer);
    mapObj.initwindow();
    var m_temp_source = new Cesium.CustomDataSource("tempSourceLayer");
    viewer.dataSources.add(m_temp_source);
    viewer.scene.postProcessStages.fxaa.enabled = true;

    //initOverview(viewer);
    m_MeasureManager = new MeasureManager(viewer)
    leftclick();
    courser();
    f_MapInit();
}
const addWorldTerrainAsync = async (viewer) => {
    try {
        var customTerrainProvider = new Cesium.CesiumTerrainProvider({
            url: m_ServerInof.dem,
            requestVertexNormals: true // 根据需要确定是否需要法线
        });
        viewer.terrainProvider = customTerrainProvider;
    } catch (error) {

    }
};

function f_ClearEntities(type, code) {
    if (type) {
        for (var i = viewer.entities.values.length - 1; i >= 0; i--) {
            if (code) {
                if (
                    viewer.entities.values[i].type == type &&
                    Number(viewer.entities.values[i].code) == code
                ) {
                    viewer.entities.remove(viewer.entities.values[i]);
                }
            } else {
                if (viewer.entities.values[i].type == type) {
                    viewer.entities.remove(viewer.entities.values[i]);
                }

            }
        }
        if (code == 0 && braid) {
            braid.destroy(); //关闭事件句柄
            braid = null;
        }
    } else {
        for (var i = viewer.entities.values.length - 1; i >= 0; i--) {
            if (!viewer.entities.values[i].type) {
                viewer.entities.remove(viewer.entities.values[i]);
            }
        }
    }
}

//恒定事件(高度、点击)
function leftclick() {
    // // 叠加地形服务
    // var terrainUrls = new Array();

    // for (var i = 0; i < subdomains.length; i++){
    //     var url = tdtUrl.replace('{s}', subdomains[i]) + 'DataServer?T=elv_c&tk=' + wapworldToken;
    //     terrainUrls.push(url);
    // }

    // var provider = new Cesium.GeoTerrainProvider({
    //     urls: terrainUrls
    // });

    // viewer.terrainProvider = provider;
    //Cesium 监听相机高度变化
    viewer.camera.changed.addEventListener(function (percentage) {
        var heading = viewer.scene.camera.heading;
        const m_roll = Cesium.Math.toDegrees(heading);
        const image = document.getElementById('m_zbz');
        const angle = -1 * m_roll;
        image.style.transform = `rotate(${angle}deg)`;
    });
    // viewer.scene.screenSpaceCameraController.maximumZoomDistance = 1000000; //相机高度的最大值
    // viewer.scene.screenSpaceCameraController.minimumZoomDistance = 100;
    //cesium监听相机事件
    setTimeout(() => {
        viewer.scene.camera.moveEnd.addEventListener(function (e, s) {
            //计算镜头范围方法，该方法会计算当前镜头地理坐标（弧度）范围并返回west,east,north,south 4个范围参数
            // let rectangle = viewer.camera.computeViewRectangle();
            let Cartesian3 = f_GetCurCameraInfo();
            // if (Cesium.Math.toDegrees(Cartesian3.pitch) < -75) {
            //     f_SetMapView(
            //         Cartesian3.heading,
            //         Cesium.Math.toRadians(-70),
            //         Cartesian3.roll,
            //         Cartesian3.lon,
            //         Cartesian3.lat,
            //         Cartesian3.height
            //     );
            // }
            // if (Cesium.Math.toDegrees(Cartesian3.pitch) > -15) {
            //     f_SetMapView(
            //         Cartesian3.heading,
            //         Cesium.Math.toRadians(-20),
            //         Cartesian3.roll,
            //         Cartesian3.lon,
            //         Cartesian3.lat,
            //         Cartesian3.height
            //     );
            // }
        });
    }, 3000);
    let handler3D = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
    //左键键操作
    handler3D.setInputAction(function (movement) {
        let pick = viewer.scene.pick(movement.position);

        let cartesian3 = viewer.scene.globe.pick(
            viewer.camera.getPickRay(movement.position),
            viewer.scene
        );
        let cartographic = Cesium.Cartographic.fromCartesian(cartesian3);
        let lat = Cesium.Math.toDegrees(cartographic.latitude);
        let lng = Cesium.Math.toDegrees(cartographic.longitude);
        mapObj.f_eventCheck(lng, lat, movement)

        if (pick) {
            if (pick.id) {
                if (pick.id.type == "dj") {
                    mapObj.setPopupPos(cartesian3, pick.id);
                } else if (pick.id.type == "video") {
                    mainStore().videoData = pick.id;
                    mainStore().videoPopShow = true;
                } else if (pick.id.type == "gk") {
                    mainStore().carlogData = pick.id;
                    mainStore().carlogShow = true;
                } else if (pick.id.type == "team") {
                    mainStore().teamData = pick.id;
                    mainStore().teamShow = true;
                } else if (pick.id.type == "warehouse") {
                    mainStore().warehouseData = pick.id;
                    mainStore().warehouseShow = true;
                } else if (pick.id.type == "fhgk") {
                    mainStore().compositePopShow = true;
                    mainStore().videoData = pick.id;
                    mainStore().carlogData = pick.id;
                } else {
                    mapObj.clearPopup();
                }
            } else {
                mapObj.clearPopup();
            }
            return;
        } else {
            mapObj.clearPopup();
        }
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
    //右键操作
    handler3D.setInputAction(function (click) {
        if (mStore().$state.gather) {
            f_ClearEntities(1100);
            // mStore().changeGather(false);
            // mStore().changePunctuation("show", false);
            ElMessage("已取消标点添加！");
        }
    }, Cesium.ScreenSpaceEventType.RIGHT_CLICK);

    //监听鼠标滚轮事件
    handler3D.setInputAction((wheelment) => {
        //从Cesium中获取当前地图瓦片等级
        let tilesToRender = viewer.scene.globe._surface._tilesToRender;
        if (Cesium.defined(tilesToRender)) {
            var strZoom = "";
            for (let i = 0; i < tilesToRender.length; i++) {
                if (i == 0) {
                    strZoom = tilesToRender[i].level;
                }
            }
        }
    }, Cesium.ScreenSpaceEventType.WHEEL);
}

function f_GetTerrainHeight(movement) {
    var ray = viewer.camera.getPickRay(movement.position);
    var cartesian1 = viewer.scene.globe.pick(ray, viewer.scene);
    var cartographic1 = Cesium.Cartographic.fromCartesian(cartesian1);
    var height = cartographic1.height;//的值为地形高度

    return height;
}
function f_ShowGridMap(isChecked) {
    if (!isChecked) {
        objGrid.show = false;
    } else {
        objGrid.show = true;
    }
    m_GridShow = !m_GridShow;
    m_MapGridRender = !m_MapGridRender;
}
function courser() {
    var myhandler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
    myhandler.setInputAction(function (movement) {
        var pic = viewer.scene.pick(movement.endPosition);
        if (pic) {
            viewer.enableCursorStyle = false;
            viewer._element.style.cursor = "";
            document.documentElement.style.cursor = "pointer";
        } else {
            viewer.enableCursorStyle = true;
            document.documentElement.style.cursor = "";
        }
    }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
}
//双图对比控制同步
function initHandler(v1, v2) {
    // var _self=null;
    // console.log(95,v1, v2, 'self');
    let handler = new Cesium.ScreenSpaceEventHandler(v1.scene.canvas);
    let handler1 = new Cesium.ScreenSpaceEventHandler(v2.scene.canvas);
    if (
        handler &&
        handler.getInputAction(Cesium.ScreenSpaceEventType.MOUSE_MOVE)
    ) {
        return;
    }
    handler.setInputAction(function (movement) {
        var _camerca = v1.camera;
        v2.camera.setView({
            destination: _camerca.position,
            orientation: {
                direction: _camerca._direction,
                up: _camerca.up,
                heading: _camerca.heading,
                pitch: _camerca.pitch,
                roll: _camerca.roll,
            },
        });
    }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
    handler.setInputAction(function (movement) {
        var _camerca = v1.camera;
        v2.camera.setView({
            destination: _camerca.position,
            orientation: {
                direction: _camerca._direction,
                up: _camerca.up,
                heading: _camerca.heading,
                pitch: _camerca.pitch,
                roll: _camerca.roll,
            },
        });
    }, Cesium.ScreenSpaceEventType.WHEEL);
    handler1.setInputAction(function (movement) {
        var _camerca = v2.camera;
        v1.camera.setView({
            destination: _camerca.position,
            orientation: {
                direction: _camerca._direction,
                up: _camerca.up,
                heading: _camerca.heading,
                pitch: _camerca.pitch,
                roll: _camerca.roll,
            },
        });
    }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);

    handler1.setInputAction(function (movement) {
        var _camerca = v2.camera;
        v1.camera.setView({
            destination: _camerca.position,
            orientation: {
                direction: _camerca._direction,
                up: _camerca.up,
                heading: _camerca.heading,
                pitch: _camerca.pitch,
                roll: _camerca.roll,
            },
        });
    }, Cesium.ScreenSpaceEventType.WHEEL);
}
function clearHandler() {
    var _self = this;
    if (_self.handler) {
        _self.handler.removeInputAction(Cesium.ScreenSpaceEventType.MOUSE_MOVE);
        _self.handler.removeInputAction(Cesium.ScreenSpaceEventType.WHEEL);
    }
    if (_self.handler1) {
        _self.handler1.removeInputAction(
            Cesium.ScreenSpaceEventType.MOUSE_MOVE
        );
        _self.handler1.removeInputAction(Cesium.ScreenSpaceEventType.WHEEL);
    }
}
//地图控件控制
function mapset(v) {
    v.timeline.container.style.display = "none";
    v.cesiumWidget.creditContainer.style.display = "none";
    var stages = v.scene.postProcessStages;
    v.scene.brightness =
        v.scene.brightness ||
        stages.add(Cesium.PostProcessStageLibrary.createBrightnessStage());
    v.scene.brightness.enabled = true;
    v.scene.brightness.uniforms.brightness = Number(1.2);
    v.scene.globe.depthTestAgainsTerrain = false;
    var CesiumViewerSceneController = v.scene.screenSpaceCameraController;
    CesiumViewerSceneController.inertiaSpin = 0.95;
    CesiumViewerSceneController.inertiaTranslate = 0.95;
    CesiumViewerSceneController.inertiaZoom = 0.9;

    v.scene.postProcessStages.fxaa.enabled = true;
    var supportsImageRenderingPixelated =
        v.cesiumWidget._supportsImageRenderingPixelated;
    if (supportsImageRenderingPixelated) {
        var vtxf_dpr = window.devicePixelRatio;
        while (vtxf_dpr >= 2.0) {
            vtxf_dpr /= 2.0;
        }
        v.resolutionScale = vtxf_dpr;
    }

    v.scene.globe.baseColor = new Cesium.Color(0, 0.02, 0.23, 1.0);
    // Cesium.Camera.DEFAULT_VIEW_RECTANGLE = Cesium.Rectangle.fromDegrees(
    //     80,
    //     22,
    //     130,
    //     50
    // );
    v.scene.skyBox.show = true;
    //判断viewer的区别
    var containID = v._container.id;
    if (containID == "cesiumContainer") {
        //获取鼠标实时位置
        var handler = new Cesium.ScreenSpaceEventHandler(v.scene.canvas);
        handler.setInputAction(function (movement) {
            let ellipsoid = viewer.scene.globe.ellipsoid;
            let cartesian = viewer.scene.camera.pickEllipsoid(
                movement.endPosition,
                ellipsoid
            );

            if (cartesian) {
                let cartographic = ellipsoid.cartesianToCartographic(cartesian);
                try {
                    //调用窗口中显示距离的方法
                    window.ceshi({
                        lon: Cesium.Math.toDegrees(cartographic.longitude),
                        lat: Cesium.Math.toDegrees(cartographic.latitude),
                        height: Math.ceil(
                            viewer.camera.positionCartographic.height
                        ),
                    });
                } catch (ee) { }
            } else {
            }
        }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);

        //双击获取坐标
        // handler.setInputAction(function (movement) {
        //     var geom = {};
        //     let ellipsoid = viewer.scene.globe.ellipsoid;
        //     var position = viewer.scene.camera.pickEllipsoid(movement.position, ellipsoid);
        //     if (position) {
        //         var cartographic = ellipsoid.cartesianToCartographic(position);
        //         var lon = Cesium.Math.toDegrees(cartographic.longitude);
        //         var lat = Cesium.Math.toDegrees(cartographic.latitude);
        //         var height = Math.ceil(viewer.camera.positionCartographic.height);
        //         geom.lon = lon;
        //         geom.lat = lat;
        //         geom.height = height;
        //     }
        //     window.outgeom(geom)
        // }, Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK);
    } else {
    }
}

var objGrid = null;

//监听鼠标滚轮事件
var m_GridShow = true;
var m_MapGridRender = true;
var layer_qqwx;
var layer_jzwx;
var layer_dzmap;
var layer_asdz;
//地图底图图层控制
function layset(vv) {
    vv.imageryLayers.remove(vv.imageryLayers.get(0));
    var allMap = new Cesium.UrlTemplateImageryProvider({
        url: m_ServerInof.wx,
        tilingScheme: new Cesium.WebMercatorTilingScheme(),
        minimumLevel: 1,
        maximumLevel: 20,
    });
    layer_qqwx = vv.imageryLayers.addImageryProvider(allMap);
    layer_qqwx.alpha = 0.3;
    layer_qqwx.show = false;

    var jzMap1 = new Cesium.UrlTemplateImageryProvider({
        url: m_ServerInof.jzwx,
        tilingScheme: new Cesium.WebMercatorTilingScheme(),
        minimumLevel: 1,
        maximumLevel: 20,
    });
    layer_jzwx = vv.imageryLayers.addImageryProvider(jzMap1);
    layer_jzwx.show = false;

    var aswx = new Cesium.UrlTemplateImageryProvider({
        url: m_ServerInof.asdz,
        tilingScheme: new Cesium.WebMercatorTilingScheme(),
        minimumLevel: 1,
        maximumLevel: 20,
    });

    layer_asdz = vv.imageryLayers.addImageryProvider(aswx);
    layer_asdz.alpha = 0.5;
    layer_asdz.show = true;

    var dzmap = new Cesium.UrlTemplateImageryProvider({
        url: m_ServerInof.dzmp,
        tilingScheme: new Cesium.WebMercatorTilingScheme(),
        minimumLevel: 1,
        maximumLevel: 20,
    });
    layer_dzmap = vv.imageryLayers.addImageryProvider(dzmap);
    layer_dzmap.show = false;
}
function ckDgt() {
    let flag = true;
    if (localStorage.getItem('dgtmap') == 'true') {
        flag = true;
    } else {
        flag = false;
    }
    return flag;
}
function LayerSwitch(dgtshow) {
    if (dgtshow) {
        layer_qqwx.show = false;
        layer_jzwx.show = false;
        layer_dzmap.show = false;
        layer_asdz.show = true;
    } else {
        layer_qqwx.show = true;
        layer_jzwx.show = true;
        layer_dzmap.show = false;
        layer_asdz.show = false;
    }
}
function qqwxshow(ischecked) {
    layer_qqwx.show = ischecked;
}
function jzwxshow(ischecked) {
    layer_jzwx.show = ischecked;
}
function dzmapshow(ischecked) {
    layer_dzmap.show = ischecked;
} function asdzshow(ischecked) {
    layer_asdz.show = ischecked;
}
function addmaplayer(e) {
    viewer.imageryLayers.remove(viewer.imageryLayers._layers[2]);
    var zmdmap = e;
    viewer.imageryLayers.addImageryProvider(
        new Cesium.UrlTemplateImageryProvider({
            url: zmdmap,
            tilingScheme: new Cesium.WebMercatorTilingScheme(),
            minimumLevel: 1,
            maximumLevel: 21,
        })
    );
}

function layseAlpha(index, show, x) {
    let activeMap = x ? viewer2 : viewer;
    if (index == 16) {
        activeMap.imageryLayers.get(3).alpha = show;
        return;
    } else if (index == 17) {
        activeMap.imageryLayers.get(4).alpha = show;
        return;
    }
    activeMap.imageryLayers.get(index).alpha = show;
}


function f_Setmap(url, n, x) {
    if (!url) {
        objGrid = viewer.imageryLayers.addImageryProvider(
            new Cesium.UrlTemplateImageryProvider({
                url: layerMapdata.grid,
                tilingScheme: new Cesium.WebMercatorTilingScheme(),
                minimumLevel: 1,
                maximumLevel: 14,
            })
        );
        objGrid.show = true;
        objGrid.alpha = 0.8;
        return;
    }
    let activeMap = viewer;
    if (x) {
        activeMap = viewer2;
    }
    if (n == "ok") {
        activeMap.imageryLayers.addImageryProvider(
            new Cesium.UrlTemplateImageryProvider({
                url: url,
                tilingScheme: new Cesium.WebMercatorTilingScheme(),
                minimumLevel: 1,
                maximumLevel: 21,
            })
        ).show = false;
        return activeMap.imageryLayers._layers.length - 1;
    } else {
        activeMap.imageryLayers.get(url).show = n;
    }
}
function removeGDLK() {
    console.log(viewer.imageryLayers._layers, 'layer');
    viewer.imageryLayers._layers.forEach((item, index) => {
        if (item._imageryProvider.url.indexOf('mapabc') != -1) {
            viewer.imageryLayers.remove(viewer.imageryLayers._layers[index])
        }
    })
}
function LKshade() {
    const maskpointArray = [
        114.37890000, 37.50972584293000,
        121.28906250000000, 37.50972584293000,
        121.28906250000001, 42.35854391749000,
        114.37890525, 42.35854391749705,];
    var maskspoint = Cesium.Cartesian3.fromDegreesArray(maskpointArray);
    const entity1 = new Cesium.Entity({
        id: 1,
        polygon: {
            hierarchy: {
                //外框界
                positions: Cesium.Cartesian3.fromDegreesArray([
                    // 100, 0, 100, 89, 150, 89, 150, 0,
                    113.37890625, 37.50972584293751, 121.28906250000001,
                    37.50972584293751, 121.28906250000001, 42.35854391749705,
                    113.37890625, 42.35854391749705, 113.37890625, 37.50972584293751,
                ]),
                //挖洞
                holes: [
                    {
                        positions: maskspoint,
                    },
                ],
            },
            material: Cesium.Color.fromCssColorString("#0C1F34"),
        }
    })
    viewer.entities.add(entity1);
}

function GDlkmap() {
    // viewer.imageryLayers.remove(viewer.imageryLayers._layers[2]);

    // var lkmap = 'http://nrp.yugaosu.com/amap/traffictile?v=1.0&t=1&x={x}&y={y}&z={z}&t=' + getTimeStamp();
    var lkmap =
        "/mapabc/traffictile?v=1.0&t=1&x={x}&y={y}&z={z}&t=" +
        getTimeStamp();
    viewer.imageryLayers.addImageryProvider(
        new Cesium.UrlTemplateImageryProvider({
            url: lkmap,
            tilingScheme: new AmapMercatorTilingScheme(),
            name: 'gdlk',
            minimumLevel: 1,
            maximumLevel: 20,
        })
    );
    // LKshade();
}

//获取时间戳
function getTimeStamp() {
    let nowDate = new Date();
    let year = nowDate.getFullYear();
    let month = nowDate.getMonth() + 1;
    let today = nowDate.getDate();
    let hours = nowDate.getHours();
    let min = nowDate.getMinutes();
    let seconds = nowDate.getSeconds();
    if (month >= 1 && month <= 9) {
        month = "0" + month;
    }
    if (today >= 1 && today <= 9) {
        today = "0" + today;
    }
    if (seconds >= 1 && seconds <= 9) {
        seconds = "0" + seconds;
    }
    let currentdate =
        year +
        "-" +
        month +
        "-" +
        today +
        " " +
        hours +
        ":" +
        min +
        ":" +
        seconds;
    let longTime = new Date(
        currentdate.replace(new RegExp("-", "gm"), "/")
    ).getTime();
    console.log(longTime, currentdate);
    return longTime;
}

//墨卡托坐标初始化为经纬度坐标之后定位
function flyto(wkt, n) {
    wkt = wkt.replaceAll("POINT(", "");
    wkt = wkt.replaceAll(")", "");
    let xy = wkt.split(" ");
    let lng = (parseFloat(xy[0]) / 20037508.34) * 180;
    let lat = (parseFloat(xy[1]) / 20037508.34) * 180;
    lat =
        (180 / Math.PI) *
        (2 * Math.atan(Math.exp((lat * Math.PI) / 180)) - Math.PI / 2);
    if (!n) {
        Zoomto(lng, lat, 1000.0);
    } else {
        return [lng, lat];
    }
}

//经纬度坐标定位
async function Zoomto(x, y, h) {
    // console.log(6166, x, y, h);
    if (h) {
        return await viewer.camera.flyTo({
            destination: Cesium.Cartesian3.fromDegrees(x, y, h),
        });
    }
    if (y == 1) {
        return await viewer.flyTo(x);
    } else {
        await viewer.camera.flyTo({
            destination: new Cesium.Cartesian3(
                x.x - 830,
                x.y + 2000,
                x.z + 320
            ),
            orientation: {
                // 指向
                heading: 8.881784197001252e-16,
                // 视角
                pitch: -1.0707963267948966,
                roll: 0,
            },
        });
        if (y) {
            setTimeout(() => {
                for (var i = viewer.entities.values.length - 1; i >= 0; i--) {
                    if (
                        viewer.entities.values[i].type == 1011 &&
                        Number(viewer.entities.values[i].code) == y.id
                    ) {
                        viewer.flyTo(viewer.entities.values[i]);
                    }
                }
            }, 3000);
        }
    }
}
/**
 * 加载3DTile
 * @param {string} url
 * @param {number} height
 */
function f_LoadTile(url, height) {
    var tileset = new Cesium.Cesium3DTileset({
        url: url,
    });

    var obj = viewer.scene.primitives.add(tileset);

    tileset.readyPromise.then(function (argument) {
        var cartographic = Cesium.Cartographic.fromCartesian(
            tileset.boundingSphere.center
        );
        var surface = Cesium.Cartesian3.fromRadians(
            cartographic.longitude,
            cartographic.latitude,
            cartographic.height
        );
        var offset = Cesium.Cartesian3.fromRadians(
            cartographic.longitude,
            cartographic.latitude,
            cartographic.height + height
        );
        var translation = Cesium.Cartesian3.subtract(
            offset,
            surface,
            new Cesium.Cartesian3()
        );
        tileset.modelMatrix = Cesium.Matrix4.fromTranslation(translation);
        tileset.tileVisible.addEventListener(function (tile) {
            const model = tile.content.model;
            if (Cesium.defined(model)) {
                model.maximumHeight = 0.0; // 设置3D Tile为到地面
            }
        });
    });
    viewer.zoomTo(tileset);
    return tileset;
}

export async function addThreeDTiles(id, url, height) {
    viewer.scene.globe.depthTestAgainstTerrain = true;
    let tilesets = viewer.scene.primitives.add(
        new Cesium.Cesium3DTileset({
            // url: "http://125.46.5.250:9736/3d/dfd/tileset.json",
            url: url,
        })
    );
    tilesets.readyPromise.then(tileset => {
        var heightOffset = -200;
        var boundingSphere = tileset.boundingSphere;
        //获取3Dtlies的范围中心点的弧度
        var cartographic = Cesium.Cartographic.fromCartesian(boundingSphere.center);
        //定义3Dtlies改变之后中心点的弧度

        var surface = Cesium.Cartesian3.fromRadians(cartographic.longitude, cartographic.latitude, cartographic.height);
        //模型改变的位置
        var offset = Cesium.Cartesian3.fromRadians(cartographic.longitude, cartographic.latitude, height);

        //定义模型的改变状态
        var translation = Cesium.Cartesian3.subtract(offset, surface, new Cesium.Cartesian3());
        tileset.modelMatrix = Cesium.Matrix4.fromTranslation(translation);

    });
    // Red Hammer
    viewer.zoomTo(tilesets);
    m_3dtile = tilesets;
    return tilesets;
}
//模型泛光
var tileLight;
async function addLightTile(light) {
    f_remove3Dtile();
    viewer.scene.globe.enableLighting = true;
    viewer.scene.light = new Cesium.DirectionalLight({
        direction: new Cesium.Cartesian3(0.354925, -1.1290918, 1.383358)
    });
    viewer.scene.light.color = new Cesium.Color(1.0, 1.0, 1.0, 1.0);
    viewer.scene.light.intensity = 4;

    viewer.scene.globe.depthTestAgainstTerrain = true;
    Cesium.ExperimentalFeatures.enableModelExperimental = true;
    let tilesets = viewer.scene.primitives.add(
        new Cesium.Cesium3DTileset({
            // url: "http://125.46.5.250:9736/3d/dfd/tileset.json",
            url: "./data/tileset.json",
        })
    );
    tileLight = tilesets;
    tilesets.readyPromise.then(function (tileset) {
        // tileset.style = new Cesium.Cesium3DTileStyle({
        //     color: {
        //         conditions: [["true", "color('rgba(5, 99, 182,0.7)')"]],
        //     },
        // });

    });
    // viewer.zoomTo(tilesets);

    var customShader = new Cesium.CustomShader({
        lightingModel: Cesium.LightingModel.UNLIT,
        fragmentShaderText: `
            void fragmentMain(FragmentInput fsInput, inout czm_modelMaterial material)
            {
              vec4 position = czm_inverseModelView * vec4(fsInput.attributes.positionEC,1); // 位置

              // 注意shader中写浮点数是，一定要带小数点，否则会报错，比如0需要写成0.0，1要写成1.0
              float _baseHeight = 0.5; // 物体的基础高度，需要修改成一个合适的建筑基础高度
              float _heightRange = 10.0; // 高亮的范围(_baseHeight ~ _baseHeight + _heightRange)
              float _glowRange = 200.0; // 光环的移动范围(高度)

              // 建筑基础色
               float mars_height = position.z - _baseHeight;
              // float mars_a11 = fract(czm_frameNumber / 120.0) * 3.14159265 * 2.0;
              // float mars_a12 = mars_height / _heightRange + sin(mars_a11) * 0.1;
              // material.diffuse = vec3(0.0, 0.2, 0.8); // 颜色
              // material.diffuse *= vec3(mars_a12);// 渐变
              // 动态光环
              float time = fract(czm_frameNumber / 360.0);
              time = abs(time - 0.5) * 1.0;
              float mars_h = clamp(mars_height / _glowRange, 0.0, 1.0);
              float mars_diff = step(0.005, abs(mars_h - time));
              material.diffuse += material.diffuse * (1.0 - mars_diff);
            } `,
    });
    if (light) {
        tilesets.customShader = customShader;
    }

}
//道路流光
var roadLight;
function f_RoadLight() {
    // return;
    let features;
    axios.get('/data/zx.json').then(res => {
        features = res.data.features
        const instance = [];
        if (features?.length) {
            features.forEach((item) => {
                const arr = item.geometry.coordinates;
                arr.forEach((el) => {
                    let arr1 = [];
                    el.forEach((_el) => {
                        arr1 = arr1.concat(_el);
                    });
                    const polyline = new Cesium.PolylineGeometry({
                        positions: Cesium.Cartesian3.fromDegreesArray(arr1),
                        width: 5,
                        vertexFormat: Cesium.PolylineMaterialAppearance.VERTEX_FORMAT, // 顶点属性，默认即可
                    });
                    const geometry = Cesium.PolylineGeometry.createGeometry(polyline);
                    instance.push(
                        new Cesium.GeometryInstance({
                            geometry,
                        })
                    );
                });
            })
            let source = `czm_material czm_getMaterial(czm_materialInput materialInput)
            {
               czm_material material = czm_getDefaultMaterial(materialInput);
               vec2 st = materialInput.st;
               vec4 colorImage = texture2D(image, vec2(fract((st.s - speed * czm_frameNumber * 0.001)), st.t));
               material.alpha = colorImage.a * color.a;
               material.diffuse = colorImage.rgb * 1.5 ;
               return material;
            }`;
            const material = new Cesium.Material({
                fabric: {
                    uniforms: {
                        color: Cesium.Color.fromCssColorString("#7ffeff"),
                        image: "/img/line.png",
                        speed: 8
                    },
                    source,
                },
                translucent: function () {
                    return true;
                },
            });
            const appearance = new Cesium.PolylineMaterialAppearance();
            appearance.material = material;
            const primitive = new Cesium.Primitive({
                geometryInstances: instance,
                appearance,
                asynchronous: false,
            });
            roadLight = primitive;
            viewer.scene.primitives.add(roadLight);
        }
    })
}
//流光飞线
function generateRandomLines(center, num) {
    let geometryInstances = []
    for (let i = 0; i < num; i++) {
        let lon = center[0] + (Math.random() - 0.5) * 0.1;
        let lat = center[1] + (Math.random() - 0.5) * 0.1;
        const geometry = new Cesium.PolylineGeometry({
            positions: Cesium.Cartesian3.fromDegreesArrayHeights([
                lon, lat, 0, lon, lat, 5000 * Math.random()
            ]),
            width: 1.0,
        })
        const instance = new Cesium.GeometryInstance({ geometry: geometry })
        geometryInstances.push(instance)
    }
    return geometryInstances
}
var m_LightFly;
function LightFly() {
    const fragmentShaderSource = `
        uniform vec4 color;
        uniform float speed;
        uniform float percent;
        uniform float gradient;
        
        czm_material czm_getMaterial(czm_materialInput materialInput){
          czm_material material = czm_getDefaultMaterial(materialInput);
          vec2 st = materialInput.st;
          float t = fract(czm_frameNumber * speed / 1000.0);
          t *= (1.0 + percent);
          float alpha = smoothstep(t- percent, t, st.s) * step(-t, -st.s);
          alpha += gradient;
          material.diffuse = color.rgb;
          material.alpha = alpha;
          material.emission = vec3(0.7);
          return material;
        }
        `
    m_LightFly = new Cesium.Primitive({
        geometryInstances: generateRandomLines([113.1147, 35.2150], 40),
        appearance: new Cesium.PolylineMaterialAppearance({
            material: new Cesium.Material({
                fabric: {
                    uniforms: {
                        color: new Cesium.Color(0, 0, 1, 1),
                        speed: 10.0,
                        percent: 0.2,
                        gradient: 0.00
                    },
                    source: fragmentShaderSource
                },
            }),
        }),
        allowPicking: false
    })
    viewer.scene.primitives.add(m_LightFly)
}

function removePrimitives() {
    removeLightFly();
    removeTileLight();
    removeWater();
}
function removeRoadLight() {
    viewer.scene.primitives.remove(roadLight);
}
function removeLightFly() {
    viewer.scene.primitives.remove(m_LightFly);
}
function removeTileLight() {
    viewer.scene.primitives.remove(tileLight);
}
function removeWater() {
    m_water.forEach((item) => {
        viewer.scene.primitives.remove(item);
    })
}
var m_water = [];
function waterM() {
    axios.get('./data/sx.json').then(res => {
        m_water = [];
        res.data.features.forEach(item => {
            item.geometry.coordinates.forEach(coord => {
                // console.log(coord[0].flat());
                let m_polygon = new Cesium.PolygonGeometry({
                    polygonHierarchy: new Cesium.PolygonHierarchy(
                        Cesium.Cartesian3.fromDegreesArray(coord[0].flat())
                    ),
                    height: 0.5
                })
                let geometry = Cesium.PolygonGeometry.createGeometry(m_polygon);
                let instance = new Cesium.GeometryInstance({
                    geometry: geometry,
                })
                let material = new Cesium.Material({
                    fabric: {
                        type: 'Water',
                        uniforms: {
                            baseWaterColor: new Cesium.Color(64 / 255.0, 157 / 255.0, 253 / 255.0, 0.5),
                            normalMap: './img/water.jpg',
                            frequency: 1000.0,
                            animationSpeed: 0.1,
                            amplitude: 10,
                            specularIntensity: 10
                        }
                    }
                })
                let appearance = new Cesium.EllipsoidSurfaceAppearance({
                    material: material
                })
                let obj = viewer.scene.primitives.add(new Cesium.Primitive({
                    geometryInstances: instance,
                    appearance: appearance,
                    asynchronous: false,
                }))
                m_water.push(obj);
            })
        })
    })
}
//拉起白模型
function whiteModel() {
    axios.get('/data/jzw.json').then(res => {
        res.data.features.forEach((item, index) => {
            // console.log(item,'features');
            item.geometry.coordinates.forEach(coord => {
                viewer.entities.add({
                    wall: {
                        positions: Cesium.Cartesian3.fromDegreesArray(coord[0].flat()),
                        maximumHeights: new Array(Cesium.Cartesian3.fromDegreesArray(coord[0].flat()).length).fill(item.properties.gd + 2),
                        minimumHeights: new Array(Cesium.Cartesian3.fromDegreesArray(coord[0].flat()).length).fill(0),
                        material: new Cesium.Color(1.0, 1.0, 1.0, 1)
                        // material:new Cesium.WallDiffuseMaterialProperty({
                        //     color: new Cesium.Color(1.0, 1.0, 0.0, 1.0)
                        // })
                    },
                    polygon: {
                        hierarchy: Cesium.Cartesian3.fromDegreesArray(coord[0].flat()),
                        width: 2,
                        material: new Cesium.Color(1.0, 1.0, 1.0, 1),
                        height: item.properties.gd
                    }
                })
            })
        })
    })
}
/**
 * 加载虚幻导出模型
 * @param {string} url
 * @param {number} height
 */
function f_UELoadTile(url, height) {
    var tileset = new Cesium.Cesium3DTileset({
        url: url,
    });
    viewer.scene.primitives.add(tileset);
    viewer.zoomTo(tileset);
    tileset.readyPromise.then(function (argument) {
        tileSetAll(tileset, 113.8236212, 34.8434313, -75, 0, 0, 0, 1);
    });
    return tileset;
}
//处理模型
function tileSetAll(
    tileset,
    longitude,
    latitude,
    height,
    rotateX,
    rotateY,
    rotateZ,
    scale
) {
    //旋转角度设置
    var mx = Cesium.Matrix3.fromRotationX(Cesium.Math.toRadians(rotateX));
    var my = Cesium.Matrix3.fromRotationY(Cesium.Math.toRadians(rotateY));
    var mz = Cesium.Matrix3.fromRotationZ(Cesium.Math.toRadians(rotateZ));
    var rotationX = Cesium.Matrix4.fromRotationTranslation(mx);
    var rotationY = Cesium.Matrix4.fromRotationTranslation(my);
    var rotationZ = Cesium.Matrix4.fromRotationTranslation(mz);
    //平移 修改经纬度
    var position = Cesium.Cartesian3.fromDegrees(longitude, latitude, height);
    var transform = Cesium.Transforms.eastNorthUpToFixedFrame(position);
    //旋转、平移矩阵相乘
    Cesium.Matrix4.multiply(transform, rotationX, transform);
    Cesium.Matrix4.multiply(transform, rotationY, transform);
    Cesium.Matrix4.multiply(transform, rotationZ, transform);
    //缩放 修改缩放比例
    var scale1 = Cesium.Matrix4.fromUniformScale(scale);
    Cesium.Matrix4.multiply(transform, scale1, transform);
    //赋值给tileset
    tileset._root.transform = transform;
}
/**
 * 添加实体标注
 * @param {Array<number>} data
 */
async function f_AddPoi(data, i) {
    f_ClearEntities(1100);
    if (i) {
        await Zoomto(JSON.parse(data.position), data);
    } else {
        let POI = viewer.entities.add({
            position: Cesium.Cartesian3.fromDegrees(
                Number(data.displayX),
                Number(data.displayY),
                1000.0
            ),
            type: 1100,
            label: {
                text: data.name,
                font: "14pt monospace",
                style: Cesium.LabelStyle.FILL_AND_OUTLINE,
                outlineWidth: 2,
                pixelOffset: new Cesium.Cartesian2(0, 0),
                verticalOrigin: Cesium.VerticalOrigin.TOP,
            },
        });
        viewer.flyTo(POI);
    }
}
function cehis() {

}

window.f_ClearEntities = f_ClearEntities;
/**
 * 自定义require
 * @param {string} name 文件名
 */
function myrequire(name) {
    return new URL(`../../assets/icon/${name}.png`, import.meta.url).href;
}
/**
 * rgba颜色转换
 */
function colorConvert(Color) {
    let text = Color.substring(5);
    let borderColorString = text.substring(0, text.length - 1);
    let borderColor = borderColorString.split(",");
    return new Cesium.Color(
        Number(borderColor[0]) / 255,
        Number(borderColor[1]) / 255,
        Number(borderColor[2]) / 255,
        Number(borderColor[3])
    );
}

/**
 * 自定义添加图标和文字
 * @param {string} name 标注名称
 * @param {number} code 标识
 * @param {number} type 类型
 * @param {Array<number>} xy 坐标
 * @param {number} fontSize 文字大小
 * @param {string} color 文字颜色
 * @param {number} groundClearance 显示高度
 * @param {string} url 图标名称
 * @param {number} width 图标宽度
 * @param {number} height 图标高度
 */
function f_AddDimension(
    name,
    code,
    type,
    xy,
    fontSize,
    color,
    groundClearance,
    url,
    width,
    height
) {
    viewer.entities.add({
        name: name,
        code: code,
        type: type,
        position: Cesium.Cartesian3.fromDegrees(xy[0], xy[1], 10),
        label: {
            text: type != 1003 ? name : "",
            font: `${fontSize}pt yahei`,
            style: Cesium.LabelStyle.FILL_AND_OUTLINE, // FILL_AND_OUTLINE填充和轮廓
            verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
            pixelOffset: new Cesium.Cartesian2(0, -16),
            fillColor: new Cesium.Color.fromCssColorString(color),
            outlineWidth: 1,
            outlineColor: Cesium.Color.WHEAT,
            distanceDisplayCondition: new Cesium.DistanceDisplayCondition(
                0,
                groundClearance
            ), //当缩放到一定程度时隐藏该实体,不设置则一直显示
        },
        billboard: {
            image:
                type != 1003
                    ? new URL(`../../assets/icon/${url}.png`, import.meta.url).href
                    : new URL(`../../assets/gsname/${url}.png`, import.meta.url)
                        .href,
            width: width,
            height: height,
            distanceDisplayCondition: new Cesium.DistanceDisplayCondition(
                0,
                groundClearance
            ), //当缩放到一定程度时隐藏该实体,不设置则一直显示
        },
    });
}

/**
 * 收费站或服务区显隐
 * @param {number} type 图标类型1004/1005
 * @param {boolean} show 显隐
 */
function entitiesShow(type, show) {
    console.log(viewer.dataSources);
    viewer.dataSources._dataSources.forEach((elsiem) => {
        if (elsiem.type == type) {
            elsiem.entities.values.forEach((element) => {
                element._show = show;
            });
        }
    });
}
/**
 * 添加实体线
 * @param {array<number>} geom 坐标数组
 */
function f_AddPolyLine(geom) {
    var obj = viewer.entities.add({
        // name:'myline',
        polyline: {
            positions: Cesium.Cartesian3.fromDegreesArray(geom),
            width: 5,
            material: Cesium.Color.RED,
            clampToGround: true,
        },
    });
    viewer.zoomTo(obj);
}
/**
 * 自定义添加实体线
 * @param {string} name 线名称
 * @param {number} code 标识
 * @param {number} type 类型
 * @param {array<number>} geom 坐标数组
 * @param {number} width 宽度
 * @param {string} color 颜色
 */
function f_AddPolyCustom(name, code, type, geom, width, color) {
    var obj = viewer.entities.add({
        name: name,
        code: code,
        type: type,
        polyline: {
            positions: Cesium.Cartesian3.fromDegreesArray(geom),
            width: width,
            material: new Cesium.Color.fromCssColorString(color),
            clampToGround: true,
        },
    });
    viewer.zoomTo(obj);
}

function f_LoadJson(url_json) {

    var geojsonOptions = {
        clampToGround: true, //使数据贴地
    };
    var promise = Cesium.GeoJsonDataSource.load(url_json, geojsonOptions);
    return promise;
}



/**
 * 添加管线
 * @param {array<number>} geom 坐标数组
 */
function f_AddpolylineVolume(pos) {
    f_ClearEntities();
    var obj = viewer.entities.add({
        polylineVolume: {
            positions: Cesium.Cartesian3.fromDegreesArray(pos),
            shape: computeCircle(10),
            height: 0,
            material: Cesium.Color.GREEN.withAlpha(0.5),
        },
    });
    viewer.zoomTo(obj);
}

function computeCircle(radius) {
    let positions = [];
    for (let i = 0; i < 360; i++) {
        let radis = Cesium.Math.toRadians(i);
        positions.push(
            new Cesium.Cartesian2(
                radius * Math.cos(radis),
                radius * Math.sin(radis)
            )
        );
    }
    return positions;
}

/**
 * 添加面
 * @param {Array<number>} reg 面坐标
 */
function f_AddReg(reg) {
    f_ClearEntities();
    var stripeMaterial = new Cesium.StripeMaterialProperty({
        evenColor: Cesium.Color.WHITE.withAlpha(0.5),
        oddColor: Cesium.Color.BLUE.withAlpha(0.5),
        repeat: 5.0,
    });
    // var entities = viewer.entities;
    var obj = viewer.entities.add({
        polygon: {
            hierarchy: new Cesium.PolygonHierarchy(
                Cesium.Cartesian3.fromDegreesArray(reg)
            ),
            outline: true,
            outlineColor: Cesium.Color.WHITE,
            outlineWidth: 4,
            material: stripeMaterial,
        },
    });
    viewer.zoomTo(obj);
}

/**测量面积 */
function newmesure() {
    m_MeasureManager.measurePolygon();
}
function mesurePolygon() {
    var m_cl_handler = new Cesium.ScreenSpaceEventHandler(
        viewer.scene._imageryLayerCollection
    );
    var positions = [];
    var tempPoints = [];
    var polygon = null;
    var gonfloating;
    var cartesian = null;
    m_cl_handler.setInputAction(function (movement) {
        let ray = viewer.camera.getPickRay(movement.endPosition);
        cartesian = viewer.scene.globe.pick(ray, viewer.scene);
        positions.pop(); //移除最后一个
        positions.push(cartesian);
        if (positions.length >= 2) {
            var dynamicPositions = new Cesium.CallbackProperty(function () {
                return new Cesium.PolygonHierarchy(positions);
                return positions;
            }, false);
            polygon = PolygonPrimitive(dynamicPositions);
        }
    }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);

    m_cl_handler.setInputAction(function (movement) {
        let ray = viewer.camera.getPickRay(movement.position);
        cartesian = viewer.scene.globe.pick(ray, viewer.scene);
        if (positions.length == 0) {
            positions.push(cartesian.clone());
        }
        positions.push(cartesian);
        //在三维场景中添加点
        var cartographic = Cesium.Cartographic.fromCartesian(
            positions[positions.length - 1]
        );
        var longitudeString = Cesium.Math.toDegrees(cartographic.longitude);
        var latitudeString = Cesium.Math.toDegrees(cartographic.latitude);
        var heightString = cartographic.height;
        var labelText =
            "(" +
            longitudeString.toFixed(2) +
            "," +
            latitudeString.toFixed(2) +
            ")";
        tempPoints.push({
            lon: longitudeString,
            lat: latitudeString,
            hei: heightString,
        });
        gonfloating = viewer.entities.add({
            name: "多边形面积",
            position: positions[positions.length - 1],
            point: {
                pixelSize: 5,
                color: Cesium.Color.RED,
                outlineColor: Cesium.Color.WHITE,
                outlineWidth: 2,
                heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
            },
            label: {
                font: "18px sans-serif",
                fillColor: Cesium.Color.GOLD,
                style: Cesium.LabelStyle.FILL_AND_OUTLINE,
                outlineWidth: 2,
                verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
                pixelOffset: new Cesium.Cartesian2(20, -20),
            },
        });
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK);

    m_cl_handler.setInputAction(function (movement) {
        m_cl_handler.destroy();
        positions.pop();
        var textArea = getArea(tempPoints) + "平方公里";
        viewer.entities.add({
            name: "多边形面积",
            position: positions[positions.length - 1],
            label: {
                text: textArea,
                font: "18px sans-serif",
                fillColor: Cesium.Color.GOLD,
                style: Cesium.LabelStyle.FILL_AND_OUTLINE,
                outlineWidth: 2,
                verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
                pixelOffset: new Cesium.Cartesian2(20, -40),
                heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
            },
        });
    }, Cesium.ScreenSpaceEventType.RIGHT_CLICK);
    var radiansPerDegree = Math.PI / 180;
    var degreesPerRadian = 180.0 / Math.PI; //弧度转化为角度
    function getArea(points) {
        var res = 0;
        for (let i = 0; i < points.length - 2; i++) {
            let j = (i + 1) % points.length;
            let k = (i + 2) % points.length;
            var totalAngle = Angle(points[i], points[j], points[k]);
            var dis_temp1 = distance(positions[i], positions[j]);
            var dis_temp2 = distance(positions[j], positions[k]);
            res += dis_temp1 * dis_temp2 * Math.abs(Math.sin(totalAngle));
        }
        return (res / 1000000.0).toFixed(4);
    }
    function Angle(p1, p2, p3) {
        var bearing21 = Bearing(p2, p1);
        var bearing23 = Bearing(p2, p3);
        var angle = bearing21 - bearing23;
        if (angle < 0) {
            angle += 360;
        }
        return angle;
    }
    function Bearing(from, to) {
        var lat1 = from.lat * radiansPerDegree;
        var lon1 = from.lon * radiansPerDegree;
        var lat2 = to.lat * radiansPerDegree;
        var lon2 = to.lon * radiansPerDegree;
        var angle = -Math.atan2(
            Math.sin(lon1 - lon2) * Math.cos(lat2),
            Math.cos(lat1) * Math.sin(lat2) -
            Math.sin(lat1) * Math.cos(lat2) * Math.cos(lon1 - lon2)
        );
        if (angle < 0) {
            angle += Math.PI * 2.0;
        }
        angle = angle * degreesPerRadian; //角度
        return angle;
    }

    function PolygonPrimitive(positions) {
        polygon = viewer.entities.add({
            polygon: {
                hierarchy: positions,
                material: new Cesium.Color.fromCssColorString("#FFD70003"),
            },
        });
    }

    function distance(point1, point2) {
        var point1cartographic = Cesium.Cartographic.fromCartesian(point1);
        var point2cartographic = Cesium.Cartographic.fromCartesian(point2);
        /**根据经纬度计算出距离**/
        var geodesic = new Cesium.EllipsoidGeodesic();
        geodesic.setEndPoints(point1cartographic, point2cartographic);
        var s = geodesic.surfaceDistance;
        //返回两点之间的距离
        s = Math.sqrt(
            Math.pow(s, 2) +
            Math.pow(
                point2cartographic.height - point1cartographic.height,
                2
            )
        );
        return s;
    }
}

/**切换显示模式 */
function f_ShowMapModel(type) {
    if (type == 0) {
        //3d模式
        viewer.scene.morphTo3D(1);
    } else if (type == 1) {
        // 2D 模式
        viewer.scene.morphTo2D(1);
    } else {
        // 2.5D 哥伦布模式
        viewer.scene.morphToColumbusView(1);
    }
}

/**获取摄像机高度 */
function f_GetCameraHeight() {
    var cameraPos = viewer.camera.position;
    var ellipsoid = viewer.scene.globe.ellipsoid;
    var cartographic = ellipsoid.cartesianToCartographic(cameraPos);
    var height = cartographic.height;
    return height;
}
/**放大 */
function f_ZoomIn() {
    viewer.camera.zoomIn(f_GetCameraHeight() / 2);
}
/**缩小 */
function f_ZoomOut() {
    let hh = f_GetCameraHeight();
    if (hh < 1599999.0) {
        viewer.camera.zoomOut(f_GetCameraHeight() * 1.5);
    }
}
/**全屏 */
function f_FullMap() {
    viewer.camera.setView({
        destination: Cesium.Cartesian3.fromDegrees(113.82, 34.03, 1600000.0),
        orientation: {
            roll: 0.0,
        },
    });
}
/**光照 */
function f_MapLight(e) {
    viewer.scene.Globe.enableLighting = e;
}
/**相机角度 */
function f_camerarote(e) {
    viewer.scene.screenSpaceCameraController.enableRotate = !e;
}
/**获取地图显示范围 */
function f_GetMapRect() {
    let viewerRectangle = viewer.camera.computeViewRectangle();
    let rect = {
        west: ((viewerRectangle.west / Math.PI) * 180).toFixed(6),
        south: ((viewerRectangle.south / Math.PI) * 180).toFixed(6),
        east: ((viewerRectangle.east / Math.PI) * 180).toFixed(6),
        north: ((viewerRectangle.north / Math.PI) * 180).toFixed(6),
    };
    return rect;
}
var heading = 0;
var step = 5;
var m_length = 10;
function resetGlb() {
    let position = glbentity.position._value
    heading = 0;
    let hpr = new Cesium.HeadingPitchRoll(Cesium.Math.toRadians(heading), 0, 0);
    let orientation = Cesium.Transforms.headingPitchRollQuaternion(
        position,
        hpr
    );
    glbentity.orientation._value = orientation
    // console.log(heading);
}
function moveGlb(e, type) {

    //let position = glbentity.position._value;
    let position = viewer.camera.position._value;
    if (type == 'right') {
        heading += step;
        // let hpr = new Cesium.HeadingPitchRoll(Cesium.Math.toRadians(heading), 0, 0);
        // let orientation = Cesium.Transforms.headingPitchRollQuaternion(
        //     position,
        //     hpr
        // );
        // glbentity.orientation._value = orientation
        // var pos=glbentity.position._value;
        viewer.scene.camera.setView({
            orientation: {
                heading: Cesium.Math.toRadians(heading)
            },
        });
    }
    if (type == 'left') {
        heading -= step;
        // let hpr = new Cesium.HeadingPitchRoll(Cesium.Math.toRadians(heading), 0, 0);
        // let orientation = Cesium.Transforms.headingPitchRollQuaternion(
        //     position,
        //     hpr
        // );
        // glbentity.orientation._value = orientation
        // var pos=glbentity.position._value;
        viewer.scene.camera.setView({
            orientation: {
                heading: Cesium.Math.toRadians(heading)
            },
        });
    }
    if (type == 'front') {
        var m_heading = Cesium.Math.toRadians(heading);
        if (m_heading <= Math.PI / 2) {
            m_heading = Math.PI * 2 - m_heading;
        } else if (m_heading > Math.PI / 2 && m_heading <= Math.PI) {
            m_heading = Math.PI * 1.5 - m_heading;
        } else if (m_heading > Math.PI && m_heading <= Math.PI * 1.5) {
            m_heading = Math.PI - m_heading;
        } else if (m_heading > Math.PI * 1.5 && m_heading < Math.PI * 2) {
        }
        let m_position = f_GetWGSXY(position)
        let m_mkt = convertToMercator([m_position.x, m_position.y]);
        let oc = m_length * Math.sin(m_heading);
        let ao = m_length * Math.cos(m_heading);
        let m_mkt2 = [m_mkt[0] + ao, m_mkt[1] + oc];
        if (m_heading <= Math.PI / 2) {
            m_mkt2 = [m_mkt[0] + ao, m_mkt[1] - oc];
        } else if (m_heading > Math.PI / 2 && m_heading <= Math.PI) {
            m_mkt2 = [m_mkt[0] - ao, m_mkt[1] - oc];
        } else if (m_heading > Math.PI && m_heading <= Math.PI * 1.5) {
            m_mkt2 = [m_mkt[0] - ao, m_mkt[1] + oc];
        } else if (m_heading > Math.PI * 1.5 && m_heading < Math.PI * 2) {
        }

        let wgs84 = convertToWgs84(m_mkt2);
        m_position.x = wgs84[0];
        m_position.y = wgs84[1];
        console.log(m_mkt, wgs84, 'm_mkt');
        let cartesian = new Cesium.Cartesian3.fromDegrees(m_position.x, m_position.y, m_position.z);
        //glbentity.position._value = cartesian;
        // console.log(,'hpr');
        // var pos=glbentity.position._value;
        // viewer.scene.camera.setView({
        //     destination: new Cesium.Cartesian3.fromDegrees(pos.x, pos.y, pos.z+50),
        //     orientation: {
        //         heading:Cesium.Math.toRadians(heading)
        //     },
        // });
        //viewer.trackedEntity = glbentity;
        viewer.scene.camera.setView({
            destination: cartesian
            // orientation: {
            //     pitch: -1*Math.PI/4,
            // },
        });
        // viewer.camera.lookAt(glbentity.position._value,new Cesium.Cartesian3(0, 0, 200));
    }
    // else if (type == 'rear') {
    //     cartesian = new Cesium.Cartesian3(position.x, position.y - Number(e.rear), position.z)
    //     glbentity.position._value = cartesian
    //  }
}
function setroampos() {
    var camera = viewer.scene.camera;
    camera.position = { x: -2047886.7503858877, y: 4798233.938298161, z: 3656994.8127685594 };
    viewer.camera.setView({
        orientation: {
            pitch: Cesium.Math.toRadians(0.0), // 倾斜：从水平面开始的度数
        }
    })
}
var cameraHeight;
var heading;
var pitch;
var roll;
var setStep = 0.5;
var speed = 5 * 1.5;
function moveCamera(type) {
    var camera = viewer.scene.camera;
    let ellipsoid = viewer.scene.globe.ellipsoid;
    cameraHeight = ellipsoid.cartesianToCartographic(camera.position).height;
    let moveRate = (cameraHeight / 150.0) * setStep;
    heading = camera.heading;
    pitch = camera.pitch;
    roll = camera.roll;
    let carstain = f_GetWGSXY(camera.position);
    let hei = carstain.z;
    if (hei < 2) {
        hei = 2;
        let n_pos = Cesium.Cartesian3.fromDegrees(carstain.x, carstain.y, hei);
        camera.position = n_pos;
    }
    if (type == 'left') {
        camera.lookLeft(moveRate);
    }
    if (type == 'right') {
        camera.lookRight(moveRate);
    }
    if (type == 'front') {
        camera.moveForward(speed);
    }
    if (type == 'picthUp') {
        hprSetting(0, 0.01 * setStep, 0);
    }
    if (type == 'picthDown') {
        hprSetting(0, -0.01 * setStep, 0);
    }
    if (type == 'rollLeft') {
        hprSetting(0, 0, 0.01 * setStep);
    }
    if (type == 'rollRight') {
        hprSetting(0, 0, -0.01 * setStep);
    }
    if (type == 'back') {
        camera.moveBackward(speed);
    }
    if (type == 'moveUp') {
        camera.moveUp(moveRate * 10);
    }
    if (type == 'moveDown') {
        camera.moveDown(moveRate * 10);
    }
    if (type == 'moveLeft') {
        camera.moveLeft(moveRate * 10);
    }
    if (type == 'moveRight') {
        camera.moveRight(moveRate * 10);
    }
    if (type == "translateFront") {
        camera.rotateDown(Math.PI / 3600000 * setStep)
    }
    if (type == "translateBehind") {
        camera.rotateUp(Math.PI / 3600000 * setStep)
    }
}
function f_setStep(step) {
    speed = 5;
    speed = speed * step;
}
function hprSetting(h, p, r) {
    viewer.camera.setView({
        orientation: {
            heading: heading + h,
            pitch: pitch + p,
            roll: roll + r,
        },
    });
}
function convertToWgs84(xy) {
    var R2D = 180 / Math.PI;
    var A = 6378137;
    return [
        xy[0] * R2D / A,
        (Math.PI * 0.5 - 2 * Math.atan(Math.exp(-xy[1] / A))) * R2D
    ];
}
function convertToMercator(lonLat) {
    var D2R = Math.PI / 180, A = 6378137, MAXEXTENT = 20037508342789244e-9;
    var adjusted = Math.abs(lonLat[0]) <= 180 ? lonLat[0] : lonLat[0] - sign(lonLat[0]) * 360;
    var xy = [
        A * adjusted * D2R,
        A * Math.log(Math.tan(Math.PI * 0.25 + 0.5 * lonLat[1] * D2R))
    ];
    if (xy[0] > MAXEXTENT)
        xy[0] = MAXEXTENT;
    if (xy[0] < -MAXEXTENT)
        xy[0] = -MAXEXTENT;
    if (xy[1] > MAXEXTENT)
        xy[1] = MAXEXTENT;
    if (xy[1] < -MAXEXTENT)
        xy[1] = -MAXEXTENT;
    return xy;
}

var glbentity;
function f_AddMod(url, x, y, z, scale) {
    let position = Cesium.Cartesian3.fromDegrees(x, y, z);
    let heading = Cesium.Math.toRadians(0);
    let pitch = 0;
    let roll = 0;
    let hpr = new Cesium.HeadingPitchRoll(heading, pitch, roll);
    let orientation = Cesium.Transforms.headingPitchRollQuaternion(
        position,
        hpr
    );

    glbentity = viewer.entities.add({
        position: position,
        orientation: orientation,
        model: {
            uri: url,
            scale: scale,
            sampleTerrain: true,
            // clampToGround: true,
            // heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
            distanceDisplayCondition: new Cesium.DistanceDisplayCondition(
                0,
                200000
            ),
            imageBasedLightingFactor: new Cesium.Cartesian2(1, 0.6)
        },
    });

    // return entity;
    // viewer.zoomTo(entity);
}
/**沿路径飞行 */
function f_FlyByPath(triger) {
    if (!triger) {
        f_ClearEntities();
        viewer.clock.clockRange = Cesium.ClockRange.UNBOUNDED;
        viewer.clock.shouldAnimate = false;
        return;
    }
    viewer.clock.shouldAnimate = true;
    let data = [];
    data[0] = [
        { longitude: 116.405419, dimension: 39.918034, height: 0, time: 0 },
        { longitude: 116.2821, dimension: 39.918145, height: 0, time: 40 },
        {
            longitude: 115.497402,
            dimension: 39.344641,
            height: 70000,
            time: 100,
        },
        {
            longitude: 107.942392,
            dimension: 29.559967,
            height: 70000,
            time: 280,
        },
        { longitude: 106.549265, dimension: 29.559967, height: 0, time: 360 },
    ];
    data[1] = [
        { longitude: 116.405419, dimension: 39.918034, height: 0, time: 0 },
        { longitude: 117.034586, dimension: 39.881202, height: 0, time: 40 },
        {
            longitude: 116.340088,
            dimension: 38.842224,
            height: 70000,
            time: 100,
        },
        {
            longitude: 113.489176,
            dimension: 23.464017,
            height: 70000,
            time: 280,
        },
        { longitude: 113.262084, dimension: 23.13901, height: 0, time: 360 },
    ];
    data[2] = [
        { longitude: 118.838979, dimension: 32.073514, height: 0, time: 0 },
        { longitude: 118.438838, dimension: 32.03777, height: 0, time: 40 },
        {
            longitude: 117.802406,
            dimension: 31.91231,
            height: 70000,
            time: 100,
        },
        {
            longitude: 104.043645,
            dimension: 35.993845,
            height: 70000,
            time: 280,
        },
        { longitude: 101.807224, dimension: 36.660972, height: 0, time: 360 },
    ];
    let start = Cesium.JulianDate.fromDate(new Date(2023, 3, 29));
    let stop = Cesium.JulianDate.addSeconds(
        start,
        360,
        new Cesium.JulianDate()
    );
    viewer.clock.startTime = start.clone();
    viewer.clock.currentTime = start.clone();
    viewer.clock.stopTime = stop.clone();
    viewer.clock.multiplier = 10;
    viewer.timeline.zoomTo(start, stop);
    viewer.clock.clockRange = Cesium.ClockRange.LOOP_STOP;
    for (let i = 0; i < data.length; i++) {
        let property = computeFlight(start, data[i]);
        let planeModel = viewer.entities.add({
            availability: new Cesium.TimeIntervalCollection([
                new Cesium.TimeInterval({
                    start: start,
                    stop: stop,
                }),
            ]),
            position: property,
            orientation: new Cesium.VelocityOrientationProperty(property),
            model: {
                uri: "3Dmod/Cesium_Air.glb",
                minimumPixelSize: 128,
            },
        });
        if (i == 0) {
            viewer.trackedEntity = planeModel;
        }
    }
}
/**计算飞行 */
function computeFlight(start, source) {
    let property = new Cesium.SampledPositionProperty();
    for (let i = 0; i < source.length; i++) {
        let time = Cesium.JulianDate.addSeconds(
            start,
            source[i].time,
            new Cesium.JulianDate()
        );
        let position = Cesium.Cartesian3.fromDegrees(
            source[i].longitude,
            source[i].dimension,
            source[i].height
        );
        property.addSample(time, position);
    }
    return property;
}
/**视角围绕一点旋转 */
var Exection = null;
function f_LookAtPosition(ops) {
    let position = Cesium.Cartesian3.fromDegrees(ops.lng, ops.lat, ops.height);
    let pitch = Cesium.Math.toRadians(-30);
    let angle = 360 / 30;
    let distance = 5000;
    let startTime = Cesium.JulianDate.fromDate(new Date());
    viewer.clock.startTime = startTime.clone();
    viewer.clock.currentTime = startTime.clone();
    viewer.clock.clockRange = Cesium.ClockRange.CLAMPED;
    viewer.clock.clockStep = Cesium.ClockStep.SYSTEM_CLOCK;
    let initialHeading = viewer.camera.heading;
    Exection = function TimeExecution() {
        let delTime = Cesium.JulianDate.secondsDifference(
            viewer.clock.currentTime,
            viewer.clock.startTime
        );
        let heading = Cesium.Math.toRadians(delTime * angle) + initialHeading;
        viewer.scene.camera.setView({
            destination: position,
            orientation: {
                heading: heading,
                pitch: pitch,
            },
        });
        viewer.scene.camera.moveBackward(distance);
        if (
            Cesium.JulianDate.compare(
                viewer.clock.currentTime,
                viewer.clock.stopTime
            ) >= 0
        ) {
            viewer.clock.onTick.removeEventListener(Exection);
        }
    };
    viewer.clock.onTick.addEventListener(Exection);
}
function f_ClearTick() {
    if (Exection != null) {
        viewer.clock.onTick.removeEventListener(Exection);
        Exection = null;
    }
}
//泛光
function f_AddFlashPntByXYH(x, y, h, m_color) {
    class EllipsoidFadeMaterialProperty {
        constructor(color, duration) {
            this._definitionChanged = new Cesium.Event();
            var _color = undefined;
            var _colorSubscription = undefined;
            var color = color;
            var duration = duration;
            var _time = new Date().getTime();
        }
        getType(time) {
            return "EllipsoidFade";
        }
        getValue(time, result) {
            if (!Cesium.defined(result)) {
                result = {};
            }
            result.color = Cesium.Property.getValueOrClonedDefault(
                this._color,
                time,
                Cesium.Color.WHITE,
                result.color
            );

            result.time =
                ((new Date().getTime() - this._time) % this.duration) /
                this.duration;
            return result;
        }
        equals(other) {
            return (
                this === other ||
                (other instanceof EllipsoidFadeMaterialProperty &&
                    Cesium.Property.equals(this._color, other._color))
            );
        }
    }
    Cesium.defineProperties(EllipsoidFadeMaterialProperty.prototype, {
        isConstant: {
            get: function () {
                return false;
            },
        },
        definitionChanged: {
            get: function () {
                return this._definitionChanged;
            },
        },
        color: Cesium.createPropertyDescriptor("color"),
    });
    Cesium.EllipsoidFadeMaterialProperty = EllipsoidFadeMaterialProperty;
    Cesium.Material.EllipsoidFadeType = "EllipsoidFade";
    Cesium.Material.EllipsoidFadeSource =
        "czm_material czm_getMaterial(czm_materialInput materialInput)\n" +
        "{\n" +
        "czm_material material = czm_getDefaultMaterial(materialInput);\n" +
        "material.diffuse = 1.5 * color.rgb;\n" +
        "vec2 st = materialInput.st;\n" +
        "float dis = distance(st, vec2(0.5, 0.5));\n" +
        "float per = fract(time);\n" +
        "if(dis > per * 0.5){\n" +
        "material.alpha = 0.0;\n" +
        "discard;\n" +
        "}else {\n" +
        "material.alpha = color.a  * dis / per / 1.0;\n" +
        "}\n" +
        "return material;\n" +
        "}";
    Cesium.Material._materialCache.addMaterial(
        Cesium.Material.EllipsoidFadeType,
        {
            fabric: {
                type: Cesium.Material.EllipsoidFadeType,
                uniforms: {
                    color: new Cesium.Color(1.0, 0.0, 0.0, 1),
                    time: 0,
                },
                source: Cesium.Material.EllipsoidFadeSource,
            },
            translucent: function (material) {
                return true;
            },
        }
    );

    var big = m_temp_source.entities.add({
        name: "EllipsoidFade",
        position: Cesium.Cartesian3.fromDegrees(x, y, h),
        ellipse: {
            height: 0,
            semiMinorAxis: 6000.0,
            semiMajorAxis: 6000.0,
            material: new Cesium.EllipsoidFadeMaterialProperty(m_color, 2000),
        },
    });
    big.distanceDisplayCondition = new Cesium.DistanceDisplayCondition(
        10000,
        900000
    );

    var sm = m_temp_source.entities.add({
        name: "EllipsoidFade",
        position: Cesium.Cartesian3.fromDegrees(x, y, h),
        ellipse: {
            height: 0,
            semiMinorAxis: 600.0,
            semiMajorAxis: 600.0,
            material: new Cesium.EllipsoidFadeMaterialProperty(m_color, 2000),
        },
    });
    sm.distanceDisplayCondition = new Cesium.DistanceDisplayCondition(1, 10000);
}

function animationline(pos) {
    var primitive = new Cesium.primitive({
        geometryInstances: new Cesium.GeometryInstance({
            geometry: new Cesium.PolylineGeometry({
                positions: pos,
                width: 5,
                vertexFormat: Cesium.PolylineMaterialAppearance.VERTEX_FORMAT,
            }),
            attributes: {
                color: Cesium.ColorGeometryInstanceAttribute.fromColor(
                    new Cesium.Color(1.0, 1.0, 1.0, 1.0)
                ),
            },
        }),
        appearance: new Cesium.PolylineMaterialAppearance({
            material: Cesium.Material.fromType(Cesium.Material.FadeType, {
                repeat: true,
                fadeInColor: Cesium.Color.BLUE.withAlpha(0),
                fadeOutColor: Cesium.Color.WHITE,
                time: new Cesium.Cartesian2(0.0, 0.0),
                fadeDirection: {
                    x: true,
                    y: false,
                },
            }),
        }),
    });
    return primitive;
}
//获取当前相机信息
function f_GetCurCameraInfo() {
    return {
        heading: viewer.scene.camera.heading,
        pitch: viewer.scene.camera.pitch,
        roll: viewer.scene.camera.roll,
        lon: viewer.camera.position.x,
        lat: viewer.camera.position.y,
        height: viewer.camera.position.z,
    };
}
function f_SetMapView(heading, pitch, roll, lon, lat, height) {
    // console.log(heading, pitch, roll, lon, lat, height);
    if (heading) {
        viewer.camera.flyTo({
            destination: new Cesium.Cartesian3(lon, lat, height),
            orientation: {
                // 指向
                heading: heading,
                // 视角
                pitch: pitch,
                roll: roll,
            },
        });
    } else {
        viewer.camera.flyTo({
            //摄像机在 WGS84(世界)中的最终位置坐标或从自上而下的视图中可以看到的矩形
            destination: new Cesium.Cartesian3(
                viewer.camera.position.x,
                viewer.camera.position.y,
                viewer.camera.position.z
            ),
            //包含方向和向上属性或航向、俯仰和滚动属性的物体。默认情况下，方向将指向框架的中心在3D 和负 z 方向在哥伦布视图。
            //上行方向将指向当地北部的3D 和正 y 方向的哥伦布视图。在无限滚动模式下，2D 中不使用定位。
            orientation: {
                heading: Cesium.Math.toRadians(0),
                //   pitch: Cesium.Math.toRadians(-90),
                pitch: viewer.scene.camera.pitch,
                roll: 0.0,
            },
        });
    }
}


function drawPoint(position, type) {
    return viewer.entities.add({
        name: "点几何对象",
        position: position,
        type: type ? type : 1100,
        point: {
            color: Cesium.Color.white,
            pixelSize: 10,
            disableDepthTestDistance: Number.POSITIVE_INFINITY,
            heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
        },
    });
}



/**
 * 开关地形
 * @param {Boolean} show
 */
function toggleTerrain(show, x) {
    let scene = x ? viewer2.scene : viewer.scene;
    if (show) {
        addWorldTerrainAsync(viewer)
    } else {
        scene.terrainProvider = new Cesium.EllipsoidTerrainProvider({});
    }
}


function getSpaceDistance(satrt0, end0) {
    var satrt = Cesium.Cartographic.fromDegrees(satrt0[0], satrt0[1], 0);
    var end = Cesium.Cartographic.fromDegrees(end0[0], end0[1], 0);
    var geodesic = new Cesium.EllipsoidGeodesic();
    geodesic.setEndPoints(satrt, end);
    var distance = geodesic.surfaceDistance;
    return distance;
}

function textLength(text) {
    let len = 0;
    let reg = /^[0-9a-zA-Z_]{1,}$/;
    for (let index = 0; index < text.length; index++) {
        let c = text.charAt(index);
        // if (Number(c)) {
        //     len += 0.5;
        // }
        if (reg.test(c)) {
            // console.log(c);
            len += 0.5;
        } else {
            len++;
        }
    }
    return len;
    // return Math.ceil(len);  //向下取整
    // return Math.floor(len); //向上取整
}

function drawTextRote(fontSize, text) {
    var c = document.createElement("canvas");
    const d = textLength(text + "") * fontSize;
    c.width = d;
    c.height = fontSize;
    // c.style.transform = "rotate(-45deg)";
    // c.style.transformOrigin = "left bottom";
    var ctx = c.getContext("2d");
    ctx.fillStyle = "#ffffff";
    ctx.font = "bold " + fontSize + "px 微软雅黑"; //设置字体
    // ctx.textBaseline = "hanging"; //在绘制文本时使用的当前文本基线
    //绘制文本
    // ctx.translate(c.width / 2, c.height / 2);
    ctx.rotate(-1 * Math.PI / 10);
    ctx.textBaseline = "hanging";
    ctx.fillText(text, 0, 0);
    return c;
}

function drawText(fontSize, text) {
    var c = document.createElement("canvas");
    const d = textLength(text + "") * fontSize;
    c.width = d;
    c.height = fontSize;
    var ctx = c.getContext("2d");
    ctx.fillStyle = "#ffffff";
    ctx.font = "bold " + fontSize + "px 微软雅黑"; //设置字体
    ctx.textBaseline = "hanging"; //在绘制文本时使用的当前文本基线
    //绘制文本
    ctx.fillText(text, 0, 0);
    return c;
}

// function f_Add3DStereoscopic(embryo, code, type) {
//     f_ClearEntities(1100);
//     f_ClearEntities(1101);
//     let minHight = 200;
//     let maxHight = minHight;
//     let position = mStore().$state.punctuation.position;
//     if (embryo.position) position = JSON.parse(embryo.position);
//     let x = toRaw(position[0]);
//     let y = toRaw(position[1]);
//     let dis = getSpaceDistance(x, y);
//     let m_wid = dis / embryo.name.length;
//     maxHight = minHight + m_wid;
//     return viewer.entities.add({
//         type,
//         code,
//         embryo,
//         wall: {
//             positions: Cesium.Cartesian3.fromDegreesArray([
//                 x[0],
//                 x[1],
//                 y[0],
//                 y[1],
//             ]),
//             minimumHeights: [minHight, minHight],
//             maximumHeights: [maxHight, maxHight],
//             material: new Cesium.ImageMaterialProperty({
//                 image: drawText(512, embryo.name),
//                 transparent: true,
//                 color: colorConvert(embryo.stereoscopicColor),
//             }),
//         },
//     });
// }
async function f_AddPyramid(embryo) {
    f_ClearEntities(1100);
    if (!embryo) return;
    let polyCenter = null;
    if (embryo.type == 4)
        polyCenter = Cesium.Cartesian3.fromDegrees(112.659462, 34.566414, 1000);
    if (embryo.type == 3)
        polyCenter = Cesium.Cartesian3.fromDegrees(112.940226, 34.623979, 20);
    if (embryo.type == 2)
        polyCenter = Cesium.Cartesian3.fromDegrees(113.133221, 34.691088, 20);
    if (embryo.type == 1)
        polyCenter = Cesium.Cartesian3.fromDegrees(113.357487, 34.692586, 20);

    let hpr = new Cesium.HeadingPitchRoll(Cesium.Math.toRadians(180), 0, 0);
    let orientation = Cesium.Transforms.headingPitchRollQuaternion(
        polyCenter,
        hpr
    );
    let entity = viewer.entities.add({
        name: embryo.name,
        type: 1100,
        position: polyCenter,
        // orientation: orientation,    //方向
        // model: {
        //     uri: "./3Dmod/q.glb",
        //     // uri: "./3Dmod/zhui.glb",
        //     minimumPixelSize: 48,
        //     maximumScale: 100000,
        //     scale: 1.0,
        //     distanceDisplayCondition: new Cesium.DistanceDisplayCondition(
        //         0,
        //         150000
        //     ),
        // },
        label: {
            text: embryo.name,
            font: "20px 微软雅黑",
            fillColor: Cesium.Color.RED,
            pixelOffset: new Cesium.Cartesian2(0, -60),
            outlineColor: Cesium.Color.WHITE,
            outlineWidth: 5,
            style: Cesium.LabelStyle.FILL_AND_OUTLINE,
            verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
            distanceDisplayCondition: new Cesium.DistanceDisplayCondition(
                0,
                150000
            ),
        },
    });
    let position = Cesium.Cartesian3.fromDegrees(112.659462, 34.566414, 0);
    let hpRoll = new Cesium.HeadingPitchRoll(
        Cesium.Math.toRadians(90),
        0,
        Cesium.Math.toRadians(0)
    );
    let m = Cesium.Transforms.eastNorthUpToFixedFrame(
        Cesium.Cartesian3.fromDegrees(112.659462, 34.566414, 0)
    );
    let m1 = Cesium.Matrix3.fromRotationZ(Cesium.Math.toRadians(-90));
    Cesium.Matrix4.multiplyByMatrix3(m, m1, m);
    viewer.scene.primitives.add(Cesium.Model.fromGltf({
        url: "./3Dmod/zhui.glb",
        modelMatrix: Cesium.Transforms.headingPitchRollToFixedFrame(position, hpRoll),
        // modelMatrix: m,
        show: true,                     // default
        scale: 3.0,
        maximumScale: 1
    }))

    const primitives = viewer.scene.primitives;
    const length = primitives.length;
    for (let i = 0; i < length; ++i) {
        const p = primitives.get(i);
        console.log(p);
    }
    return entity;
}

// import colors1 from "/map3D/colors1.png";
function liudong() {
    let center = { lon: 113.4868202825309, lat: 34.69790455463026 };
    let cities = [{ lon: 112.49281700209367, lat: 34.55678905515026 }];
    let positions = JSON.parse(
        "[112.61417168736487,34.95329455243536,112.90338060161486,34.959566663503374,113.14778747211899,34.96904529746231,112.75320800438612,34.824216147854024]"
    );
    fluidPolyline.liudongxian(
        viewer,
        Cesium.Color.RED,
        colors1,
        3000,
        center,
        cities
    );
    fluidPolylinetrend.liudongxian(
        viewer,
        Cesium.Color.ORANGE,
        colors1,
        2000,
        positions
    );
}
window.liudong = liudong;
///huang
function f_GetCurView() {
    var obj = mapObj.f_GetCurCameraInfo();
    console.log(111, obj);
}

//贴地字
function f_Add3Dfont(text, arrmxy, color, hei) {
    //console.log(222, text, arrmxy, color);
    viewer.entities.add({
        type: "mfont",
        polygon: {
            hierarchy: Cesium.Cartesian3.fromDegreesArray(arrmxy),
            material: new Cesium.ImageMaterialProperty({
                image: drawTextRote(1024, text),
                transparent: true,
                color: color,
                outline: true,
                outlineColor: Cesium.Color.RED
            }),
            height: hei,
            // extrudedHeight:2,
            distanceDisplayCondition: new Cesium.DistanceDisplayCondition(
                10,
                800000
            ),
        },
    });
}
var m_BianJieSource = null;

function f_AddBjLine() {
    if (!m_BianJieSource) {
        m_BianJieSource = new Cesium.CustomDataSource("mBianJieSource");
        viewer.dataSources.add(m_BianJieSource);
    }
    axios.get('./data/bj.json').then(res => {
        let features = res.data.features;
        const instances = [];
        for (let i = 0; i < features.length; i++) {
            for (let j = 0; j < features[i].geometry.coordinates.length; j++) {
                const polygonArray = features[i].geometry.coordinates[j].toString().split(',');
                for (let k = 0; k < polygonArray.length; k++) {
                    polygonArray[k] = Number(polygonArray[k]);
                }
                m_BianJieSource.entities.add({
                    type: "wall",
                    polyline: {
                        positions: Cesium.Cartesian3.fromDegreesArray(polygonArray),
                        clampToGround: true,
                        heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
                        material: Cesium.Color.DEEPSKYBLUE.withAlpha(0.4),
                        width: 4
                    },
                });
            }
        }
        console.log(m_BianJieSource, 'm_BianJieSource');
    });
    axios.get('./data/r_xianjie.json').then(res => {
        let features = res.data.features;
        const instances = [];
        for (let i = 0; i < features.length; i++) {
            for (let j = 0; j < features[i].geometry.coordinates.length; j++) {
                const polygonArray = features[i].geometry.coordinates[j].toString().split(',');
                for (let k = 0; k < polygonArray.length; k++) {
                    polygonArray[k] = Number(polygonArray[k]);
                }
                m_BianJieSource.entities.add({
                    type: "wall",
                    polyline: {
                        positions: Cesium.Cartesian3.fromDegreesArray(polygonArray),
                        clampToGround: true,
                        heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
                        material: Cesium.Color.GRAY.withAlpha(0.3),
                        width: 2
                    },
                });
            }
        }
    });

}
function f_ClearBjLine() {
    m_BianJieSource.entities.removeAll();
}

function f_DrawReg(arrmxy, color) {
    //console.log(222, text, arrmxy, color);
    return viewer.entities.add({
        type: "mfont",
        polygon: {
            hierarchy: Cesium.Cartesian3.fromDegreesArray(arrmxy),
            material: new Cesium.Color.fromCssColorString("#FFD70003")
        },

    });
}
function f_Add3Dfont2(text, arrmxy, color, hei) {
    console.log(222, text, arrmxy, color);
    return viewer.entities.add({
        type: "mfont",
        polygon: {
            hierarchy: Cesium.Cartesian3.fromDegreesArray(arrmxy),
            material: new Cesium.ImageMaterialProperty({
                //image: drawText(1024, text),
                transparent: true,
                color: color,
                outline: true,
                outlineColor: Cesium.Color.RED
            }),
            height: hei,
            distanceDisplayCondition: new Cesium.DistanceDisplayCondition(
                0,
                800000
            ),
        },

    });
}

function addOuteWall(minheight, maxheight) {
    f_ClearEntities('wall');
    axios.get("./data/dfd.json").then(res => {
        //动态墙材质
        function DynamicWallMaterialProperty(options) {
            // 默认参数设置
            this._definitionChanged = new Cesium.Event();
            this._color = undefined;
            this._colorSubscription = undefined;
            this._image = undefined;
            this.color = options.color;
            this.duration = options.duration;
            // this.image = imgUrl;
            this.trailImage = options.trailImage;
            this._time = (new Date()).getTime();
        }
        Object.defineProperties(DynamicWallMaterialProperty.prototype, {
            isConstant: {
                get: function () {
                    return false;
                }
            },
            definitionChanged: {
                get: function () {
                    return this._definitionChanged;
                }
            },
            color: Cesium.createPropertyDescriptor('color')
        });
        DynamicWallMaterialProperty.prototype.getType = function (time) {
            return 'DynamicWall';
        };
        DynamicWallMaterialProperty.prototype.getValue = function (time, result) {
            if (!Cesium.defined(result)) {
                result = {};
            }
            result.color = Cesium.Property.getValueOrClonedDefault(this._color, time, Cesium.Color.WHITE, result.color);
            if (this.trailImage) {
                result.image = this.trailImage;
            } else {
                result.image = Cesium.Material.DynamicWallImage
            }

            if (this.duration) {
                result.time = (((new Date()).getTime() - this._time) % this.duration) / this.duration;
            }
            viewer.scene.requestRender();
            return result;
        };
        DynamicWallMaterialProperty.prototype.equals = function (other) {
            return this === other ||
                (other instanceof DynamicWallMaterialProperty &&
                    Cesium.Property.equals(this._color, other._color))
        };
        Object.DynamicWallMaterialProperty = DynamicWallMaterialProperty;
        Cesium.Material.DynamicWallType = 'DynamicWall';
        Cesium.Material.DynamicWallImage = "./img/mertiral.png";
        Cesium.Material.DynamicWallSource = "czm_material czm_getMaterial(czm_materialInput materialInput)\n\
                                            {\n\
                                            czm_material material = czm_getDefaultMaterial(materialInput);\n\
                                            vec2 st = materialInput.st;\n\
                                            vec4 colorImage = texture2D(image, vec2(fract(st.t - time), st.t));\n\
                                            vec4 fragColor;\n\
                                            fragColor.rgb = color.rgb / 1.0;\n\
                                            fragColor = czm_gammaCorrect(fragColor);\n\
                                            material.alpha = colorImage.a * color.a;\n\
                                            material.diffuse = color.rgb;\n\
                                            material.emission = fragColor.rgb;\n\
                                            return material;\n\
                                            }";
        Cesium.Material._materialCache.addMaterial(Cesium.Material.DynamicWallType, {
            fabric: {
                type: Cesium.Material.DynamicWallType,
                uniforms: {
                    color: new Cesium.Color(1.0, 1.0, 1.0, 1),
                    image: Cesium.Material.DynamicWallImage,
                    time: 0
                },
                source: Cesium.Material.DynamicWallSource
            },
            translucent: function (material) {
                return true;
            }
        });
        let features = res.data.features;
        const instances = [];
        for (let i = 0; i < features.length; i++) {
            for (let j = 0; j < features[i].geometry.coordinates.length; j++) {
                const polygonArray = features[i].geometry.coordinates[j].toString().split(',');
                for (let k = 0; k < polygonArray.length; k++) {
                    polygonArray[k] = Number(polygonArray[k]);
                }

                var arrPostion = [];
                var hei = 240;
                for (let k = 0; k < polygonArray.length; k++) {
                    if (isInterger(k, 2) && k > 0) {
                        arrPostion.push(hei);
                    }
                    arrPostion.push(polygonArray[k]);
                    if (k == polygonArray.length - 1) {
                        arrPostion.push(hei);
                    }
                }

                //console.log(222, arrPostion);
                viewer.entities.add({
                    type: "wall",
                    wall: {
                        //positions: Cesium.Cartesian3.fromDegreesArray(polygonArray),
                        positions: Cesium.Cartesian3.fromDegreesArrayHeights(arrPostion),
                        maximumHeights: new Array(Cesium.Cartesian3.fromDegreesArray(polygonArray).length).fill(40),
                        minimumHeights: new Array(Cesium.Cartesian3.fromDegreesArray(polygonArray).length).fill(0),
                        //clampToGround: true,
                        //heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
                        material: new Object.DynamicWallMaterialProperty({
                            color: Cesium.Color.fromBytes(6, 107, 194).withAlpha(0.7),
                            duration: 2000
                        }),
                        distanceDisplayCondition: new Cesium.DistanceDisplayCondition(
                            0,
                            100000
                        ),
                    },
                });
            }
        }
    })
}
function addTestWall() {
    f_ClearEntities('wall');
    function DynamicWallMaterialProperty(options) {
        // 默认参数设置
        this._definitionChanged = new Cesium.Event();
        this._color = undefined;
        this._colorSubscription = undefined;
        this._image = undefined;
        this.color = options.color;
        this.duration = options.duration;
        // this.image = imgUrl;
        this.trailImage = options.trailImage;
        this._time = (new Date()).getTime();
    }
    Object.defineProperties(DynamicWallMaterialProperty.prototype, {
        isConstant: {
            get: function () {
                return false;
            }
        },
        definitionChanged: {
            get: function () {
                return this._definitionChanged;
            }
        },
        color: Cesium.createPropertyDescriptor('color')
    });
    DynamicWallMaterialProperty.prototype.getType = function (time) {
        return 'DynamicWall';
    };
    DynamicWallMaterialProperty.prototype.getValue = function (time, result) {
        if (!Cesium.defined(result)) {
            result = {};
        }
        result.color = Cesium.Property.getValueOrClonedDefault(this._color, time, Cesium.Color.WHITE, result.color);
        if (this.trailImage) {
            result.image = this.trailImage;
        } else {
            result.image = Cesium.Material.DynamicWallImage
        }

        if (this.duration) {
            result.time = (((new Date()).getTime() - this._time) % this.duration) / this.duration;
        }
        viewer.scene.requestRender();
        return result;
    };
    DynamicWallMaterialProperty.prototype.equals = function (other) {
        return this === other ||
            (other instanceof DynamicWallMaterialProperty &&
                Cesium.Property.equals(this._color, other._color))
    };
    Object.DynamicWallMaterialProperty = DynamicWallMaterialProperty;
    Cesium.Material.DynamicWallType = 'DynamicWall';
    Cesium.Material.DynamicWallImage = "./img/mertiral.png";
    Cesium.Material.DynamicWallSource = "czm_material czm_getMaterial(czm_materialInput materialInput)\n\
                                        {\n\
                                        czm_material material = czm_getDefaultMaterial(materialInput);\n\
                                        vec2 st = materialInput.st;\n\
                                        vec4 colorImage = texture2D(image, vec2(fract(st.t - time), st.t));\n\
                                        vec4 fragColor;\n\
                                        fragColor.rgb = color.rgb / 1.0;\n\
                                        fragColor = czm_gammaCorrect(fragColor);\n\
                                        material.alpha = colorImage.a * color.a;\n\
                                        material.diffuse = color.rgb;\n\
                                        material.emission = fragColor.rgb;\n\
                                        return material;\n\
                                        }";
    Cesium.Material._materialCache.addMaterial(Cesium.Material.DynamicWallType, {
        fabric: {
            type: Cesium.Material.DynamicWallType,
            uniforms: {
                color: new Cesium.Color(1.0, 1.0, 1.0, 1),
                image: Cesium.Material.DynamicWallImage,
                time: 0
            },
            source: Cesium.Material.DynamicWallSource
        },
        translucent: function (material) {
            return true;
        }
    });
    axios.get('./data/test.json').then(res => {
        let features = res.data.features;
        let positions = [];
        let maximumHeights = [];
        let minimumHeights = [];
        console.log(features, 'features');
        let coordinates = features[0].geometry.coordinates[0]
        for (let i = 0; i < coordinates.length; i++) {
            let item = coordinates[i];
            positions.push(item[0])
            positions.push(item[1])
            maximumHeights.push(item[2] - 120)
            minimumHeights.push(0)
        }
        viewer.entities.add({
            type: "wall",
            wall: {
                positions: Cesium.Cartesian3.fromDegreesArray(positions),
                maximumHeights: maximumHeights,
                minimumHeights: minimumHeights,
                outline: false,
                outlineColor: Cesium.Color.LIGHTGRAY,
                outlineWidth: 4,
                // material: Cesium.Color.GRAY,
                material: new Object.DynamicWallMaterialProperty({
                    color: Cesium.Color.fromBytes(6, 107, 194).withAlpha(0.8),
                    duration: 2000
                }),

            },
        });

    })

}
function clearWall() {
    f_ClearEntities('wall');
}
function isInterger(obj, num) {
    return obj % num === 0
}
var m_arrDM = [];
function f_DrawDM() {
    m_arrDM = [];
    let shi = f_LoadJson("./data/p_shi.json");
    setTimeout(async () => {
        if (shi != null) {
            await shi.then(function (dataSource) {
                m_arrDM.push(dataSource);
                viewer.dataSources.add(dataSource);
                let entities = dataSource.entities.values;
                for (let i = 0; i < entities.length; i++) {
                    let entity = entities[i];
                    entity.billboard = null;
                    entity.label = {
                        scale: 1,
                        font: "20px '微软雅黑',Arial,Helvetica,sans-serif,Helvetica",
                        outlineWidth: 3.0,
                        outlineColor: Cesium.Color.BLACK,
                        style: Cesium.LabelStyle.FILL_AND_OUTLINE,
                        verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
                        horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
                        text: entity.name,//图标名称
                        zIndex: 90,
                        fillColor: Cesium.Color.fromCssColorString("#ff0000"),
                        heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
                        //pixelOffset: new Cesium.Cartesian2(0, -30),
                        //scaleByDistance: new Cesium.NearFarScalar(1000, 1.8, 500000, 0.5),
                        distanceDisplayCondition:
                            new Cesium.DistanceDisplayCondition(
                                0,
                                500000
                            ),
                    }
                    //console.log(111,entity);
                }
            })

        }
    }, 0);
    let xian = f_LoadJson("./data/p_xian.json");
    setTimeout(async () => {
        if (xian != null) {
            await xian.then(function (dataSource) {
                m_arrDM.push(dataSource);
                viewer.dataSources.add(dataSource);
                let entities = dataSource.entities.values;
                for (let i = 0; i < entities.length; i++) {
                    let entity = entities[i];
                    entity.billboard = null;
                    entity.label = {
                        scale: 1,
                        font: "19px '微软雅黑',Arial,Helvetica,sans-serif,Helvetica",
                        outlineWidth: 3.0,
                        outlineColor: Cesium.Color.BLACK,
                        style: Cesium.LabelStyle.FILL_AND_OUTLINE,
                        verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
                        horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
                        zIndex: 18,
                        text: entity.name,//图标名称
                        heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
                        fillColor: Cesium.Color.fromCssColorString("#ff9205"),
                        //pixelOffset: new Cesium.Cartesian2(0, -20),
                        //scaleByDistance: new Cesium.NearFarScalar(1000, 2.0, 200000, 0.8),
                        distanceDisplayCondition:
                            new Cesium.DistanceDisplayCondition(
                                0,
                                500000
                            ),
                    }
                    //console.log(111,entity);
                }
            })

        }
    }, 0);
    let obj_gd = f_LoadJson("./data/p_xz.json");
    setTimeout(async () => {
        if (obj_gd != null) {
            await obj_gd.then(function (dataSource) {
                m_arrDM.push(dataSource);
                viewer.dataSources.add(dataSource);
                let entities = dataSource.entities.values;
                for (let i = 0; i < entities.length; i++) {
                    let entity = entities[i];
                    entity.billboard = null;
                    entity.label = {
                        scale: 1,
                        font: "16px '微软雅黑'",
                        outlineWidth: 3.0,
                        outlineColor: Cesium.Color.BLACK,
                        style: Cesium.LabelStyle.FILL_AND_OUTLINE,
                        verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
                        horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
                        text: entity.name,//图标名称
                        zIndex: 11,
                        heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
                        fillColor: Cesium.Color.DEEPSKYBLUE,
                        //pixelOffset: new Cesium.Cartesian2(0, 1),
                        //scaleByDistance: new Cesium.NearFarScalar(50000, 1.2, 500000, 0.5),
                        distanceDisplayCondition:
                            new Cesium.DistanceDisplayCondition(
                                0,
                                100000
                            ),
                    }
                }
            })

        }
    }, 0);
    let obj_cun = f_LoadJson("./data/p_cun.json");
    setTimeout(async () => {
        if (obj_cun != null) {
            await obj_cun.then(function (dataSource) {
                m_arrDM.push(dataSource);
                viewer.dataSources.add(dataSource);
                let entities = dataSource.entities.values;
                for (let i = 0; i < entities.length; i++) {
                    let entity = entities[i];
                    entity.billboard = null;
                    entity.label = {
                        scale: 1,
                        font: "14px '微软雅黑'",
                        outlineWidth: 3.0,
                        outlineColor: Cesium.Color.BLACK,
                        style: Cesium.LabelStyle.FILL_AND_OUTLINE,
                        verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
                        horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
                        //style: Cesium.LabelStyle.FILL,
                        text: entity.name,//图标名称
                        zIndex: 11,
                        heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
                        fillColor: Cesium.Color.fromCssColorString("#ffff"),
                        //pixelOffset: new Cesium.Cartesian2(0, 1),
                        //scaleByDistance: new Cesium.NearFarScalar(50000, 1.2, 500000, 0.5),
                        distanceDisplayCondition:
                            new Cesium.DistanceDisplayCondition(
                                0,
                                50000
                            ),
                    }
                }
            })

        }
    }, 0);
}
function f_clearDM() {
    m_arrDM.forEach((item, index) => {
        viewer.dataSources.remove(item);
    })
    m_arrDM = [];
}


//绘制空中线
var arrRoadData = [];
function f_DrawFloatLine() {
    let obj_gd = f_LoadJson("./data/rd.json");
    setTimeout(async () => {
        if (obj_gd != null) {
            await obj_gd.then(function (dataSource) {
                //viewer.dataSources.add(dataSource);
                let entities = dataSource.entities.values;
                for (let i = 0; i < entities.length; i++) {
                    let entity = entities[i];
                    //entity.polyline=null;
                    var temp = f_GetNewPosition(entity.polyline.positions._value);

                    ///entity.polyline.width=3;
                    //entity.polyline.positions=Cesium.Cartesian3.fromDegreesArrayHeights(temp);

                    //f_DrawRoad(temp);
                    //console.log(222,temp);
                    var obj = viewer.entities.add({
                        polyline: {
                            positions: Cesium.Cartesian3.fromDegreesArrayHeights(temp),
                            width: 4,
                            material: Cesium.Color.AQUAMARINE.withAlpha(0.4)
                        }
                    });
                    arrRoadData.push(obj);
                }
            })

        }
    }, 0);


}

function f_DrawRoad(geom) {
    //var geom = [113.7018414853, 34.7759332074, 50, 113.7033153405, 34.7776102166, 50, 113.7021543859, 34.7808799076, 50, 113.7521543859, 34.7808799076, 1000];
    var obj = viewer.entities.add({
        polylineVolume: {
            positions: Cesium.Cartesian3.fromDegreesArrayHeights(geom),
            height: 0,
            shape: computeCircle(1.0),
            material: Cesium.Color.RED.withAlpha(1.0)
            //material: new Cesium.PolylineTrailLinkMaterialProperty(Cesium.Color.RED, 3000,1)
        }
    });
    //viewer.zoomTo(obj);
    return obj;
}

function f_GetNewPosition(positions) {
    var arrPost = [];
    positions.forEach((item) => {
        var xyz = f_GetWGSXY(item);
        //arrPost.push([xyz.x,xyz.y,xyz.z]);
        arrPost.push(xyz.x);
        arrPost.push(xyz.y);
        arrPost.push(xyz.z);
    });
    return arrPost;
}

function f_GetWGSXY(positionCartesian) {
    var positionWGS84 = viewer.scene.globe.ellipsoid.cartesianToCartographic(positionCartesian);
    var longitude = Cesium.Math.toDegrees(positionWGS84.longitude);
    var latitude = Cesium.Math.toDegrees(positionWGS84.latitude);
    var height = positionWGS84.height;
    return {
        x: longitude,
        y: latitude,
        z: height
    };
}

//绘制浮动字
function f_DrawFloat3dText() {
    // cityjson.features.forEach((item, index) => {
    //     let arr = []
    //     for (let i = 0; i < item.geometry.coordinates[0].length; i++) {
    //         arr = arr.concat(item.geometry.coordinates[0][i])
    //     }
    //     console.log(999,arr);
    //     f_Add3Dfont(item.properties.name, arr, new Cesium.Color.fromCssColorString("#FF0101"));
    // });
    var arr = [113.1132829335078, 35.221407999605844, 113.11245348814454, 35.2218462673586, 113.11408405914378, 35.22390570227216, 113.11491350450704, 35.223467445641184, 113.1132829335078, 35.221407999605844];
    //f_Add3Dfont("新园路", arr, new Cesium.Color.fromCssColorString("#FF0101"),200);
    // arr = [113.12691107226252, 35.221908469136096, 113.12691107226252, 35.22276406826002, 113.12974843145402, 35.22276406826002, 113.12974843145402, 35.221908469136096, 113.12691107226252, 35.221908469136096];
    // f_Add3Dfont("新园路", arr, new Cesium.Color.fromCssColorString("#FF0000"), 200);
    // f_Add3Dfont2("莲花路",arr, new Cesium.Color.fromCssColorString("#FF0101").withAlpha(0.2),200);

}

//读取倾斜摄影三维地图 
var m_3dTileObj = [];
function f_Load3DTiles(id, url, height) {
    addThreeDTiles(id, url,height);
}

function f_LoadMy3D(id, url, height) {
    var obj = f_Load3DTiles(id, url, height);
    //f_Load3DTiles('http://192.168.10.9:3003/3d/dfd/tileset.json',-121.5);
}

//删除一个3dTiles对象
function f_Clear3D(id) {
    for (var i = 0; i < m_3dTileObj.length; i++) {
        var item = m_3dTileObj[i];
        if (item.id == id) {
            viewer.scene.primitives.remove(item.obj);
            m_3dTileObj.splice(i, 1);
            break;
        }
    }
}

function f_crtSource() {
    var m_source = new Cesium.CustomDataSource("msource");
    return m_source;
}
var m_DWsourec = null;
//加载标注
var m_arrDanWeiData = [];
function f_ShowDanWei() {
    let obj_gd = f_LoadJson("./data/qy.json");
    setTimeout(async () => {
        if (obj_gd != null) {
            await obj_gd.then(function (dataSource) {
                console.log(dataSource, 'z');
                //viewer.dataSources.add(dataSource);
                let entities = dataSource.entities.values;
                for (let i = 0; i < entities.length; i++) {
                    let entity = entities[i];
                    var img = './img/sfzm.png';
                    if (entity.name.length <= 4) {
                        img = './img/sfz.png';
                    }
                    else if (entity.name.length > 4 && entity.name.length <= 7) {
                        img = './img/sfzl.png';
                    }
                    //console.log(999,entity._properties._gid._value);
                    var m_mxyz = f_GetWGSXY(entity.position._value);
                    var citizensBankPark = m_DWsourec.entities.add({
                        name: entity.name,
                        code: entity.id,
                        type: "danwei",
                        position: Cesium.Cartesian3.fromDegrees(m_mxyz.x, m_mxyz.y, 100),//xyz
                        label: { //文字标签
                            text: entity.name,
                            font: "13pt '微软雅黑'",
                            style: Cesium.LabelStyle.FILL_AND_OUTLINE,
                            verticalOrigin: Cesium.VerticalOrigin.BASELINE,
                            horizontalOrigin: Cesium.HorizontalOrigin.LEFT,
                            pixelOffset: new Cesium.Cartesian2(42, -21)   //偏移量
                            , fillColor: new Cesium.Color.fromCssColorString("#ffffff")
                            , outlineColor: Cesium.Color.BLACK
                            , outlineWidth: 2
                            , distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0, 10000)
                        },
                        billboard: { //图标
                            image: img,
                            verticalOrigin: Cesium.VerticalOrigin.BASELINE,
                            horizontalOrigin: Cesium.HorizontalOrigin.LEFT,
                            distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0, 10000)
                        }

                    });

                }
            })

        }
    }, 0);
}
function f_InitDanWei() {
    if (!m_DWsourec) {
        m_DWsourec = f_crtSource();
        viewer.dataSources.add(m_DWsourec);
    } else {

    }
}
function f_ClearDanWei() {
    m_DWsourec.entities.removeAll();
}
//绘制HTML标签
function f_DrawHTML() {

}

function f_Add3DText(text, minHight, arrmxy, color) {
    var maxHight = minHight;
    var mxy = arrmxy;
    var dis = getSpaceDistance([mxy[0], mxy[1]], [mxy[2], mxy[3]]);
    //f_DrawPoint(mxy[0], mxy[1], Cesium.Color.RED, minHight);
    //f_DrawPoint(mxy[2], mxy[3], Cesium.Color.RED, minHight);
    //var text = "郑州景观地理空间信息研究院";
    //计算每个字多少米;
    var m_wid = dis / text.length;
    maxHight = minHight + m_wid;
    const wall = viewer.entities.add({
        type: "3DText",
        wall: {
            positions: Cesium.Cartesian3.fromDegreesArray(mxy),
            minimumHeights: [minHight, minHight],
            maximumHeights: [maxHight, maxHight],
            material: new Cesium.ImageMaterialProperty({
                image: drawText(512, text),
                transparent: true,
                color: color,
            })
        },
    });
    wall.wall.rotate = Cesium.Matrix3.fromRotationZ(Cesium.Math.toRadians(0.5));
    //console.log(999,wall.wall.rotate);
}

function f_DrawPoint(x, y, color, hei) {
    var point = viewer.entities.add({
        // 设置点的位置
        position: Cesium.Cartesian3.fromDegrees(x, y, hei), // 纬度, 经度

        // 点的样式
        point: {
            // 点的颜色
            color: color,//Cesium.Color.RED
            // 点的大小，以像素为单位
            pixelSize: 10
        }
    });
}

//计算固定宽度
function f_Add3DTextByHei(text, minHight, arrmxy, color, wid) {

    var mxy = arrmxy;
    var type = 1;//表示++情况，=2 表示+-情况    
    if (arrmxy[0] > arrmxy[2]) {
        //两个点交换一下
        mxy = [arrmxy[2], arrmxy[3], arrmxy[0], arrmxy[1]];
        type = 2;
        if (mxy[3] > mxy[1]) {
            type = 1;
        }
    }
    else {
        if (arrmxy[1] > arrmxy[3]) {
            //两个点交换一下
            //mxy = [arrmxy[2], arrmxy[3], arrmxy[0], arrmxy[1]];
            type = 2;

        }
    }
    //layer.msg(type);
    //var text = "郑州景观地理空间信息研究院";
    //计算每个字多少米;
    var maxHight = minHight;
    var st1 = lonlatToMercator(mxy[0], mxy[1]);
    var st2 = lonlatToMercator(mxy[2], mxy[3]);

    //AB点总长度
    var L = f_GetDistance(st1.x, st1.y, st2.x, st2.y) / 2;
    //
    var l = wid / 2;


    //ab的中心点
    var center_pos = { x: (st1.x + st2.x) / 2, y: (st1.y + st2.y) / 2 };
    var xyz_center841 = mercatorTolonlat(center_pos.x, center_pos.y);
    //f_DrawPoint(xyz_center841.lon, xyz_center841.lat, Cesium.Color.BLUE, minHight);


    //求b点 
    if (type == 1) {
        const BO_L = Math.abs(st2.y - center_pos.y);
        const CO_L = Math.abs(st2.x - center_pos.x);
        const H = (BO_L * l) / L;
        const W = (CO_L * l) / L;
        var m_End = center_pos;

        m_End.x = center_pos.x + W;
        m_End.y = center_pos.y + H;

        var m_end84 = mercatorTolonlat(m_End.x, m_End.y);
        //f_DrawPoint(m_end84.lon, m_end84.lat, Cesium.Color.CORAL, minHight);

        var m_ks = [];
        m_ks.x = m_End.x - 2 * W;
        m_ks.y = m_End.y - 2 * H;

        var m_start84 = mercatorTolonlat(m_ks.x, m_ks.y);
        //f_DrawPoint(m_start84.lon, m_start84.lat, Cesium.Color.DODGERBLUE, minHight);

        var dis = getSpaceDistance([m_start84.lon, m_start84.lat], [m_end84.lon, m_end84.lat]);
        var m_wid = dis / text.length;
        maxHight = minHight + m_wid;

        var my_arrXY = [m_start84.lon, m_start84.lat, m_end84.lon, m_end84.lat];
        return viewer.entities.add({
            type: "3DText",
            wall: {
                positions: Cesium.Cartesian3.fromDegreesArray(my_arrXY),
                minimumHeights: [minHight, minHight],
                maximumHeights: [maxHight, maxHight],
                material: new Cesium.ImageMaterialProperty({
                    image: drawText(512, text),
                    transparent: true,
                    color: color,
                }),
            },
        });
    }
    else {
        const BO_L = Math.abs(st2.y - center_pos.y);
        const CO_L = Math.abs(st2.x - center_pos.x);
        const H = (BO_L * l) / L;
        const W = (CO_L * l) / L;
        var m_End = center_pos;

        m_End.x = center_pos.x + W;
        m_End.y = center_pos.y - H;

        var m_end84 = mercatorTolonlat(m_End.x, m_End.y);
        //f_DrawPoint(m_end84.lon, m_end84.lat, Cesium.Color.CORAL, minHight);

        var m_ks = [];
        m_ks.x = m_End.x - 2 * W;
        m_ks.y = m_End.y + 2 * H;

        var m_start84 = mercatorTolonlat(m_ks.x, m_ks.y);
        //f_DrawPoint(m_start84.lon, m_start84.lat, Cesium.Color.DODGERBLUE, minHight);

        var dis = getSpaceDistance([m_start84.lon, m_start84.lat], [m_end84.lon, m_end84.lat]);
        var m_wid = dis / text.length;
        maxHight = minHight + m_wid;

        var my_arrXY = [m_start84.lon, m_start84.lat, m_end84.lon, m_end84.lat];
        return viewer.entities.add({
            type: "3DText",
            wall: {
                positions: Cesium.Cartesian3.fromDegreesArray(my_arrXY),
                minimumHeights: [minHight, minHight],
                maximumHeights: [maxHight, maxHight],
                material: new Cesium.ImageMaterialProperty({
                    image: drawText(512, text),
                    transparent: true,
                    color: color,
                }),
            },
        });
    }
}

function f_GetDistance(x1, y1, x2, y2) {
    const dx = x2 - x1;
    const dy = y2 - y1;
    return Math.sqrt(dx * dx + dy * dy);
}

function lonlatToMercator(lon, lat) {
    var mercator = {};

    let x = lon * 20037508.34 / 180;
    let y = Math.log(Math.tan((90 + lat) * Math.PI / 360)) / (Math.PI / 180);

    y = y * 20037508.34 / 180;

    mercator.x = x;
    mercator.y = y;

    return mercator;
}

function mercatorTolonlat(xx, yy) {
    let lonlat = {};

    let x = xx / 20037508.34 * 180;
    let y = yy / 20037508.34 * 180;

    y = 180 / Math.PI * (2 * Math.atan(Math.exp(y * Math.PI / 180)) - Math.PI / 2);

    lonlat.lon = x;
    lonlat.lat = y;

    return lonlat;
};
function f_ClearRoadName(){
    f_ClearEntities('3DText');
}
function f_LoadRoadName() {
    axios.get('./config/config.json').then(res => {
        console.log(res.data[0].ServerIP, 'mres');
        m_ServerInof = res.data[0];
        var url = m_ServerInof.ServerIP + "/rname";
        axios.get(url)
            .then(res => {
                res.data.data.forEach((item) => {
                    //console.log(999, item);
                    var cor = Cesium.Color.WHITE.withAlpha(0.6);//普通路名
                    if (item.type == 2) {
                        cor = Cesium.Color.LIME.withAlpha(1.0);//高速公路
                    }
                    else if (item.type == 3) {
                        cor = Cesium.Color.YELLOW.withAlpha(0.6);//铁路
                    }
                    else if (item.type == 4) {
                        cor = Cesium.Color.CYAN.withAlpha(0.6);//河流名称
                    }
                    else if (item.type == 5) {
                        cor = Cesium.Color.RED.withAlpha(0.98);//其他单位
                    }
                    f_Add3DTextByHei(
                        item.name,
                        5,
                        [item.x1, item.y1, item.x2, item.y2],
                        cor,
                        80
                    );
                });
            })
    })
    // var serverIP = localStorage.getItem("serverIP");

}
function f_LoadRoadName2() {
    // var serverIP = localStorage.getItem("serverIP");

    var url = m_ServerInof.ServerIP + "/rname";
    // console.log(m_ServerInof.ServerIP, url, 'm_ServerInof');
    axios.get(url)
        .then(res => {
            res.data.data.forEach((item) => {
                //console.log(999, item);
                var cor = Cesium.Color.WHITE.withAlpha(0.6);//普通路名
                if (item.type == 2) {
                    cor = Cesium.Color.LIME.withAlpha(1.0);//高速公路
                }
                else if (item.type == 3) {
                    cor = Cesium.Color.YELLOW.withAlpha(0.6);//铁路
                }
                else if (item.type == 4) {
                    cor = Cesium.Color.CYAN.withAlpha(0.6);//河流名称
                }
                else if (item.type == 5) {
                    cor = Cesium.Color.RED.withAlpha(0.98);//其他单位
                }
                f_Add3DTextByHei(
                    item.name,
                    5,
                    [item.x1, item.y1, item.x2, item.y2],
                    cor,
                    80
                );
            });
        })
}
function f_remove3Dtile() {
    console.log(tileLight, 'm_3dtile');

    clearWall();
    viewer.scene.primitives.remove(
        m_3dtile
    );
}
//3维地图
function f_Load3DMapData() {
    addTestWall();
    removeTileLight();
    f_remove3Dtile();
    // axios.get('http://125.46.5.250:2208/jc/config/config.json')
    axios.get('/config/config.json')
        .then(res => {
            m_ServerInof = res.data[0];
            let mapurl = localStorage.getItem('mapurl');
            if (!mapurl) {
                localStorage.setItem('mapurl', m_ServerInof.m_3dmap.url);
            } else {

            }
            console.log(m_ServerInof.m_3dmap.height,'m_ServerInof')
            f_Load3DTiles(m_ServerInof.m_3dmap.id, localStorage.getItem('mapurl'), m_ServerInof.m_3dmap.height);
        })
    // f_Loadsingle3DTiles(111,'/out/tileset.json',6)
}

function f_Close3DMapData() {
    f_Clear3D(m_ServerInof.m_3dmap.id);
}

function f_Msg() {
    alert("test");
}

function f_Test() {
    mapObj.f_Init();
}
function remove3Dtile() {
    for (
        let index = viewer.scene.primitives._primitives.length - 1;
        index >= 1;
        index--
    ) {
        viewer.scene.primitives.remove(
            viewer.scene.primitives._primitives[index]
        );
    }
}
function measureLine() {
    // f_ClearEntities();
    viewer.cesiumWidget.screenSpaceEventHandler.removeInputAction(
        Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK
    );
    var m_cl_handler = new Cesium.ScreenSpaceEventHandler(
        viewer.scene._imageryLayerCollection
    );
    var positions = [];
    var poly = null;
    var distance = 0;
    var cartesian = null;
    var floatingPoint;
    var labelPt = null;
    m_cl_handler.setInputAction(function (movement) {
        let ray = viewer.camera.getPickRay(movement.endPosition);
        cartesian = viewer.scene.globe.pick(ray, viewer.scene);
        if (!Cesium.defined(cartesian))
            //跳出地球时异常
            return;
        if (positions.length >= 2) {
            if (!Cesium.defined(poly)) {
                poly = new PolyLinePrimitive(positions);
            } else {
                positions.pop();
                positions.push(cartesian);
            }
        }
    }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);

    m_cl_handler.setInputAction(function (movement) {
        let ray = viewer.camera.getPickRay(movement.position);
        cartesian = viewer.scene.globe.pick(ray, viewer.scene);
        if (!Cesium.defined(cartesian))
            //跳出地球时异常
            return;
        if (positions.length == 0) {
            positions.push(cartesian.clone());
        }
        positions.push(cartesian);
        //记录鼠标单击时的节点位置，异步计算贴地距离
        labelPt = positions[positions.length - 1];
        if (positions.length > 2) {
            getSpaceDistance(positions);
        } else if (positions.length == 2) {
            //在三维场景中添加Label
            //不能添加到viewer里面，不好清除掉
            floatingPoint = viewer.entities.add({
                name: "空间距离",
                position: labelPt,
                point: {
                    pixelSize: 5,
                    color: Cesium.Color.RED,
                    outlineColor: Cesium.Color.WHITE,
                    outlineWidth: 2,
                },
            });
        }
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK);

    m_cl_handler.setInputAction(function (movement) {
        m_cl_handler.destroy(); //关闭事件句柄
        m_cl_handler = undefined;
        positions.pop(); //最后一个点无效
        if (positions.length == 1) viewer.entities.remove(floatingPoint);
    }, Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK);

    var PolyLinePrimitive = (function () {
        class _ {
            constructor(positions) {
                this.options = {
                    name: "直线",
                    polyline: {
                        show: true,
                        positions: [],
                        material: Cesium.Color.CHARTREUSE,
                        width: 3,
                        clampToGround: true,
                    },
                };
                this.positions = positions;
                this._init();
            }
            _init() {
                var _self = this;
                var _update = function () {
                    return _self.positions;
                };
                //实时更新polyline.positions
                this.options.polyline.positions = new Cesium.CallbackProperty(
                    _update,
                    false
                );
                viewer.entities.add(this.options);
            }
        }
        return _;
    })();

    //空间两点距离计算函数
    function getSpaceDistance(positions) {
        //只计算最后一截，与前面累加
        //因move和鼠标左击事件，最后两个点坐标重复
        var i = positions.length - 3;
        var point1cartographic = Cesium.Cartographic.fromCartesian(
            positions[i]
        );
        var point2cartographic = Cesium.Cartographic.fromCartesian(
            positions[i + 1]
        );
        getTerrainDistance(point1cartographic, point2cartographic);
    }

    function getTerrainDistance(point1cartographic, point2cartographic) {
        var geodesic = new Cesium.EllipsoidGeodesic();
        geodesic.setEndPoints(point1cartographic, point2cartographic);
        var s = geodesic.surfaceDistance;
        var cartoPts = [point1cartographic];
        for (var jj = 1000; jj < s; jj += 1000) {
            //分段采样计算距离
            var cartoPt = geodesic.interpolateUsingSurfaceDistance(jj);
            cartoPts.push(cartoPt);
        }
        cartoPts.push(point2cartographic);
        //返回两点之间的距离
        Cesium.sampleTerrain(viewer.terrainProvider, 8, cartoPts).then(
            (updatedPositions) => {
                for (var jj = 0; jj < updatedPositions.length - 1; jj++) {
                    var geoD = new Cesium.EllipsoidGeodesic();
                    geoD.setEndPoints(
                        updatedPositions[jj],
                        updatedPositions[jj + 1]
                    );
                    var innerS = geoD.surfaceDistance;
                    innerS = Math.sqrt(
                        Math.pow(innerS, 2) +
                        Math.pow(
                            updatedPositions[jj + 1].height -
                            updatedPositions[jj].height,
                            2
                        )
                    );
                    distance += innerS;
                }
                //在三维场景中添加Label
                var lon1 =
                    viewer.scene.globe.ellipsoid.cartesianToCartographic(
                        labelPt
                    ).longitude;
                var lat1 =
                    viewer.scene.globe.ellipsoid.cartesianToCartographic(
                        labelPt
                    ).latitude;
                var lonLat =
                    "(" +
                    Cesium.Math.toDegrees(lon1).toFixed(2) +
                    "," +
                    Cesium.Math.toDegrees(lat1).toFixed(2) +
                    ")";
                var textDisance = distance.toFixed(2) + "米";
                if (distance > 10000)
                    textDisance = (distance / 1000.0).toFixed(2) + "千米";
                floatingPoint = viewer.entities.add({
                    name: "贴地距离",
                    position: labelPt,
                    point: {
                        pixelSize: 5,
                        color: Cesium.Color.RED,
                        outlineColor: Cesium.Color.WHITE,
                        outlineWidth: 2,
                    },
                    label: {
                        text: textDisance,
                        font: "18px sans-serif",
                        fillColor: Cesium.Color.GOLD,
                        style: Cesium.LabelStyle.FILL_AND_OUTLINE,
                        outlineWidth: 2,
                        verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
                        pixelOffset: new Cesium.Cartesian2(20, -20),
                    },
                });
            }
        );
    }
}
function f_JZFullMap() {
    var obj =
    {
        "heading": 6.2001342663502195,
        "pitch": -0.6119829060635755,
        "roll": 0.0003559646884125911,
        "lon": -2052436.4918573305,
        "lat": 4803564.3622371545,
        "height": 3654788.857610189
    }
    mapObj.f_SetMapView(obj.heading, obj.pitch, obj.roll, obj.lon, obj.lat, obj.height);

}
function f_set3Dmaptype(type) {
    if (type == 1 && m_ServerInof.m_3dmap.url != localStorage.getItem('mapurl')) {
        localStorage.setItem("mapurl", m_ServerInof.m_3dmap.url);
        // return;
    }
    if (type == 2 && m_ServerInof.m_3dmap.localurl != localStorage.getItem('mapurl')) {
        localStorage.setItem("mapurl", m_ServerInof.m_3dmap.localurl);
        // return;
    }
    mapObj.f_remove3Dtile();
    f_Load3DMapData();
}
//初始化
function f_MapInit() {
    // axios.get('http://125.46.5.250:2208/jc/config/config.json')
    axios.get('/config/config.json')
        .then(res => {
            m_ServerInof = res.data[0];
            let mapurl = localStorage.getItem('mapurl');
            if (!mapurl) {
                localStorage.setItem('mapurl', m_ServerInof.m_3dmap.url);
            } else {

            }
            f_Run();
        })

    function f_Run() {

        mapset(viewer);
        layset(viewer);
        viewer.scene.screenSpaceCameraController.minimumZoomDistance = 60;
        viewer.scene.screenSpaceCameraController.maximumZoomDistance = 20000;
        // addTestWall()
        // f_JZFullMap();
        f_InitDanWei();
        // mapObj.f_AddBjLine();
        // f_ShowDanWei();
        // f_LoadRoadName();
        // model(true)
        // f_AddMod('./data/3.glb', 113.1106449, 35.2180990, 1, 1.5)
        // setTimeout(() => {
        //     mapObj.f_Loadsingle3DTiles('111', '/data/dfd/tileset.json')
        // }, 500);
        // mapObj.f_pathRun();
    }
}
function model(dgt) {
    if (dgt) {
        viewer.scene.terrainProvider = new Cesium.EllipsoidTerrainProvider({});
        // f_RoadLight();
        addLightTile();
        LightFly();
        f_clearDM();
        // whiteModel();
        waterM();
        f_ClearEntities('wall');
        f_ClearEntities('3DText');
        f_remove3Dtile();
        mapObj.f_roadPoint();
        f_LoadRoadName2();
    } else {
        removePrimitives();
        viewer.scene.globe.enableLighting = false;
        f_DrawDM();
        f_ClearEntities('3DText');

        f_LoadRoadName();
        addTestWall();
        // addOuteWall();
        f_Load3DMapData();
        // addWorldTerrainAsync(viewer); 
    }
    // mapObj.f_pathcancel();
    setTimeout(() => {
        LayerSwitch(dgt);
    }, 500)
}
function switch3DTile(type) {

    mapObj.f_remove3Dtile();
    axios.get('/config/config.json').then(res => {
        m_ServerInof = res.data[0];
        if (type == 'dfd') {
            mapObj.addThreeDTiles(m_ServerInof.m_3dmap.id, m_ServerInof.m_3dmap.dfdurl);
        } else if (type == 'all') {
            mapObj.addThreeDTiles(m_ServerInof.m_3dmap.id, m_ServerInof.m_3dmap.url);

        }
    })
}
export default {
    f_DrawDM,
    f_clearDM,
    qqwxshow,
    jzwxshow,
    dzmapshow,
    asdzshow,
    addTestWall,
    clearWall,
    f_RoadLight,
    removeRoadLight,
    f_Load3DMapData,
    f_remove3Dtile,
    waterM,
    LightFly,
    removeLightFly,
    removeTileLight,
    removeWater,
    switch3DTile,
    model,
    toggleTerrain,
    layset,
    layseAlpha,
    mapset,
    setviewer,
    f_LoadTile,
    remove3Dtile,
    f_AddPoi,
    f_AddDimension,
    entitiesShow,
    f_AddPolyLine,
    f_AddpolylineVolume,
    f_AddPolyCustom,
    f_AddReg,
    measureLine,
    mesurePolygon,
    newmesure,
    f_ShowMapModel,
    f_ZoomIn,
    f_ZoomOut,
    f_FullMap,
    f_ClearEntities,
    flyto,
    f_MapLight,
    f_camerarote,
    f_GetMapRect,
    f_AddMod,
    moveGlb,
    f_setStep,
    moveCamera,
    setroampos,
    resetGlb,
    heading,
    f_FlyByPath,
    f_ClearTick,
    f_LookAtPosition,
    Zoomto,
    f_AddFlashPntByXYH,
    animationline,
    addmaplayer,
    removeGDLK,
    GDlkmap,
    f_Setmap,
    f_GetCurCameraInfo,
    f_SetMapView,
    f_ShowGridMap,
    f_AddPyramid,
    cehis,
    liudong,
    f_GetCurView,
    f_JZFullMap,
    f_LoadMy3D,
    f_Clear3D,
    f_DrawFloat3dText,
    f_Msg,
    f_Test,
    f_set3Dmaptype,
    f_clearDM,
    f_ClearDanWei,
    f_AddBjLine,
    f_ClearBjLine,
    mapObj,
    addLightTile,
    addOuteWall,
    f_ShowDanWei,
    f_LoadRoadName,
    f_ClearRoadName
};
